ServiceLocator redivivus
This is the (so far) final form of the ServiceLocator class:
Features:
The automatic registration (the Discover() method) needs implementation classes to be decorated with the Register attribute:
Finally, I have also created a helper class for manual registration:
Decorating a class is obvious:
In the initial part of the application (like Global.asax.cs) you can do either this:
or this:
Finally (!), replace all "new class()" with:
In fact, it is recommended that you do not "hide" the dependencies, which means creating (usually) two constructors: one explicitly indicating dependencies and a default one calling the first, like this:
Whew :) Please let me know if this helps, or if you find any problems with it :)
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- namespace Helper
- {
- public static class ServiceLocator
- {
- private static readonly Dictionary<Type, Func<object>> container = new Dictionary<Type, Func<object>>();
- private static readonly object containerLock = new object();
- public static Func<Type, object> OnTypeNotFound =
- type => { throw new NotSupportedException("Cannot resolve type " + type); };
- /// <summary>
- /// Discovers all the classes decorated with the Register attribute and registers them as implementations of the ImplementedType argument
- /// </summary>
- public static void Discover()
- {
- var types = Assembly.GetCallingAssembly().GetTypes().ToList();
- types.ForEach(type =>
- {
- var attr = type.GetCustomAttribute<RegisterAttribute>();
- if (attr != null)
- Register(attr.ImplementedType, () => Activator.CreateInstance(type));
- });
- }
- /// <summary>
- /// Helper function to return a custom attribute of a specified type
- /// </summary>
- /// <typeparam name="T">Desired type for the custom attribute</typeparam>
- /// <param name="type">Type searched for the custom attribute</param>
- /// <returns>The custom attribute or null if it was not found</returns>
- private static T GetCustomAttribute<T>(this ICustomAttributeProvider type) where T : class
- {
- return type.GetCustomAttributes(typeof (T), true).FirstOrDefault() as T;
- }
- /// <summary>
- /// Maps the type T to a function returning T
- /// </summary>
- /// <typeparam name="T">Type requested by the application</typeparam>
- /// <param name="func">Function returning an instance of T</param>
- public static void Register<T>(Func<T> func) where T : class
- {
- Register(typeof (T), () => func());
- }
- /// <summary>
- /// Maps the type T to a function returning T
- /// </summary>
- /// <param name="T">Type requested by the application</param>
- /// <param name="func">Function returning an instance of T</param>
- public static void Register(Type T, Func<object> func)
- {
- if (Contains(T))
- throw new ArgumentException("Type " + T + " already registered.");
- lock (containerLock)
- container.Add(T, func);
- }
- /// <summary>
- /// Removes the association for type T (for example as a preparation for another registration)
- /// </summary>
- /// <typeparam name="T">Type to unregister</typeparam>
- public static void Unregister<T>() where T : class
- {
- Unregister(typeof (T));
- }
- /// <summary>
- /// Removes the association for type T (for example as a preparation for another registration)
- /// </summary>
- /// <param name="T">Type to unregister</param>
- public static void Unregister(Type T)
- {
- lock (containerLock)
- container.Remove(T);
- }
- /// <summary>
- /// Returns true if the type T is registered
- /// </summary>
- /// <typeparam name="T">Type to check for an existing registration</typeparam>
- /// <returns>True if T is registered</returns>
- public static bool Contains<T>() where T : class
- {
- return Contains(typeof (T));
- }
- /// <summary>
- /// Returns true if the type T is registered
- /// </summary>
- /// <param name="T">Type to check for an existing registration</param>
- /// <returns>True if T is registered</returns>
- public static bool Contains(Type T)
- {
- lock (containerLock)
- return container.ContainsKey(T);
- }
- /// <summary>
- /// This is used by the application when it needs an instance of T
- /// </summary>
- /// <typeparam name="T">Type that the application needs an instance of</typeparam>
- /// <returns>An instance of T</returns>
- public static T GetInstanceOf<T>() where T : class
- {
- return GetInstanceOf(typeof (T)) as T;
- }
- /// <summary>
- /// This is used by the application when it needs an instance of T
- /// </summary>
- /// <param name="T">Type that the application needs an instance of</param>
- /// <returns>An instance of T</returns>
- public static object GetInstanceOf(Type T)
- {
- lock (containerLock)
- {
- Func<object> result;
- if (container.TryGetValue(T, out result))
- return result();
- }
- return OnTypeNotFound != null ? OnTypeNotFound(T) : null;
- }
- }
- }
Features:
- OnTypeNotFound() - function mapping a type to an object if there is no explicit mapping for it. By default it will throw an exception, but you can replace it if you want, for example, to automatically Mock all types not explicitly mapped.
- Discover() - this will inspect the calling assembly and automatically register as implementations all types decorated with the Register attribute.
- Register() - maps a type (normally an interface type, but that's not required) to a Func<> returning an instance of that type. This allows, for example, a singleton implementation where the Func<> always returns the same object. Register() will throw if the type was already registered to avoid overwriting a registration by mistake; for intentional overwriting, use Unregister() first.
- Unregister() - removes an existing mapping; does not throw even if one does not exist.
- Contains() - can be used to verify that a type is registered, as GetInstanceOf() will by default throw if it's not.
- GetInstanceOf() - this finds the function mapped to the given type and executes it, returning its result; if a mapping for this type is not found, GetInstanceOf() returns OnTypeNotFound() - which implicitly throws but can be overwritten.
The automatic registration (the Discover() method) needs implementation classes to be decorated with the Register attribute:
- using System;
- namespace Helper
- {
- /// <summary>
- /// Use this attribute to decorate classes that should be registered as implementations of the argument
- /// </summary>
- /// <example>[Register(IRepository)]</example>
- [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
- public class RegisterAttribute : Attribute
- {
- public Type ImplementedType { get; set; }
- public RegisterAttribute()
- {
- }
- public RegisterAttribute(Type implementedType)
- {
- ImplementedType = implementedType;
- }
- }
- }
Finally, I have also created a helper class for manual registration:
- using System;
- namespace Helper
- {
- /// <summary>
- /// Fluent interface simplifying the registration of implementations
- /// </summary>
- /// <typeparam name="T">Type to implement</typeparam>
- /// <example>Bind<IRepository>.To(() => new Repository());</example>
- public static class Bind<T> where T : class
- {
- /// <summary>
- /// Maps T to Func<T>
- /// </summary>
- /// <param name="func">Function returning an instance of T</param>
- public static void To(Func<T> func)
- {
- ServiceLocator.Register(func);
- }
- }
- }
Decorating a class is obvious:
- [Register(typeof (DataContext))]
- public partial class DBDataContext
- {
- }
In the initial part of the application (like Global.asax.cs) you can do either this:
- ServiceLocator.Discover();
or this:
- Bind<DataContext>.To(() => new DBDataContext());
- Bind<IProductRepository>.To(() => new ProductRepository());
- Bind<IImageRepository>.To(() => new ImageRepository());
Finally (!), replace all "new class()" with:
- var repository = ServiceLocator.GetInstanceOf<IProductRepository>();
In fact, it is recommended that you do not "hide" the dependencies, which means creating (usually) two constructors: one explicitly indicating dependencies and a default one calling the first, like this:
- public class ProductController : Controller
- {
- private readonly IProductRepository repository;
- public ProductController() : this(ServiceLocator.GetInstanceOf<IProductRepository>())
- {
- }
- public ProductController(IProductRepository repository)
- {
- this.repository = repository;
- }
- }
Whew :) Please let me know if this helps, or if you find any problems with it :)
Comments