Nice methods in the ServiceLocator class
I just like the way these methods look. I'd take the ServiceLocator class to a job interview :)
- /// <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)
- if (container.ContainsKey(T))
- return container[T]();
- return CreateInstance(T) ?? (OnTypeNotFound != null ? OnTypeNotFound(T) : null);
- }
- /// <summary>
- /// Creates a new instance of T using the "best" constructor (the one with the biggest number of arguments that are known to the service locator, with the default constructor being the last attempt)
- /// </summary>
- /// <param name="T">Type to instantiate</param>
- /// <returns>A new instance of T or null if no suitable constructor has been found</returns>
- public static object CreateInstance(this Type T)
- {
- var constructor = GetBestConstructor(T);
- return constructor != null ? constructor.Invoke() : Activator.CreateInstance(T);
- }
- private static ConstructorInfo GetBestConstructor(Type T)
- {
- return (from c in T.GetConstructors(BindingFlags.Public)
- let parameters = c.GetParameters()
- orderby parameters.Length descending
- where parameters.All(p => Contains(p.ParameterType))
- select c)
- .FirstOrDefault();
- }
- private static object Invoke(this ConstructorInfo constructor)
- {
- var arguments = constructor
- .GetParameters()
- .Select(p => GetInstanceOf(p.ParameterType))
- .ToArray();
- return constructor.Invoke(arguments);
- }
Comments