A Simple Dependency Resolver

Inversion of control with respect to dependency resolution is usually always an issue to address in large software solutions written to perform and scale rapidly.  Here is a simple dependency resolver with an IoC gateway that can be used in the constructors of your C# classes today!

Let's start by defining the contract of the simple dependency resolver.  It's just one generically typed method; Resolve.

 

      public interface IDependencyResolver
    {
        T Resolve<T>();
    }

 

Next, a definition of the class that will provide the implementation of the Resolve method.  The essence of the SimpleDependencyResolver class is a collection of objects indexed by their type, or a dictionary, called m_Types, in which the key is a type and the value is an object of that type.  

 

      public class SimpleDependencyResolver : IDependencyResolver
    {
        private readonly Dictionary<Type, object> m_Types = new Dictionary<Type, object>();

        public T Resolve<T>()
        {
            return (T)m_Types[typeof(T)];
        }

        public void Register<T>(object obj)
        {
            if (obj is T == false)
            {
                System.Reflection.MethodBase currentMethod = System.Reflection.MethodInfo.GetCurrentMethod();
                throw new InvalidOperationException(String.Format("{0}.{1}: The supplied instance does not implement {2}.", currentMethod.DeclaringType, currentMethod.Name, typeof(T).FullName));
            }

            m_Types.Add(typeof(T), obj);
        }

        public void ClearTypesCollection()
        {
            if (m_Types != null)
            {
                m_Types.Clear();
            }
        }
    }

 

Finally, the static gateway that provides inversion of control to the contructor of the class in which dependencies need to be resolved. A sample usage follows.

 

      public class IoC
    {
        private static IDependencyResolver s_Inner;

        public static void Initialize(IDependencyResolver resolver)
        {
            s_Inner = resolver;
        }

        public static T Resolve<T>()
        {
            try
            {
                return s_Inner.Resolve<T>();
            }
            catch
            {
                return default(T);
            }
        }
    }

 

Sample usage:

 

        public CreditProcessingPage() : this(IoC.Resolve<NavigationData>()) { }

        public CreditProcessingPage(NavigationData navigationData)
        {
            InitializeComponent();

                   .
                   .
                   .
        }