Common Service Locator for MAF

Here's an implementation of the Common Service Locator for MAF:


	public class MafServiceLocator : IServiceLocator
	{
		#region Public constructor
		public MafServiceLocator()
		{
			this.Path = Environment.CurrentDirectory;
			this.Level = AddInSecurityLevel.FullTrust;
		}
		#endregion

		#region Public properties
		public String Path
		{
			get;
			set;
		}

		public AddInSecurityLevel Level
		{
			get;
			set;
		}
		#endregion

		#region IServiceLocator Members

		public IEnumerable<TService> GetAllInstances<TService>()
		{			
			AddInStore.Update(this.Path);

			foreach (AddInToken token in AddInStore.FindAddIns(typeof(TService), this.Path))
			{
				yield return (token.Activate<TService>(this.Level));
			}
		}

		public IEnumerable<Object>GetAllInstances(Type serviceType)
		{
			AddInStore.Update(this.Path);

			foreach (AddInToken token in AddInStore.FindAddIns(serviceType, this.Path))
			{
				yield return (token.Activate<Object>(this.Level));
			}
		}

		public TService GetInstance<TService>(String key)
		{
			AddInStore.Update(this.Path);

			foreach (AddInToken token in AddInStore.FindAddIns(typeof(TService), this.Path))
			{
				if (token.Name == key)
				{
					return (token.Activate<TService>(this.Level));
				}
			}

			return (default(TService));
		}

		public TService GetInstance<TService>()
		{
			AddInStore.Update(this.Path);

			foreach (AddInToken token in AddInStore.FindAddIns(typeof(TService), this.Path))
			{
				return (token.Activate<TService>(this.Level));
			}

			return (default(TService));
		}

		public Object GetInstance(Type serviceType, String key)
		{
			AddInStore.Update(this.Path);

			foreach (AddInToken token in AddInStore.FindAddIns(serviceType, this.Path))
			{
				if (token.Name == key)
				{
					return (token.Activate<Object>(this.Level));
				}
			}

			return (null);
		}

		public Object GetInstance(Type serviceType)
		{
			AddInStore.Update(this.Path);

			foreach (AddInToken token in AddInStore.FindAddIns(serviceType, this.Path))
			{
				return (token.Activate<Object>(this.Level));
			}

			return (null);
		}

		#endregion

		#region IServiceProvider Members

		public Object GetService(Type serviceType)
		{
			AddInStore.Update(this.Path);

			return (this.GetInstance(serviceType));
		}

		#endregion
	}

	ServiceLocator.SetLocatorProvider(() => new MafServiceLocator());

	IEnumerable<IOperation> operations = ServiceLocator.Current.GetAllInstances<IOperation>();

	IOperation op = ServiceLocator.Current.GetService(typeof(IOperation)) as IOperation;

Bookmark and Share

                             

No Comments