PM's Blog

Pramod Mohanan's notes about ASP.NET, MVC, C#, SQL, jQuery, Bootstrap

Configuration based Unity IOC for Dependency Injection

I have always maintained that having an IOC for DI makes only half sense if we are still registering the types in the code. The exception is when you have dynamic parameters passed into constructors of the classes being constructed by the Dependency Injection.

Here is what I mean for example instead of doing

  IUnityContainer unitycontainer = new UnityContainer();  
  unitycontainer.RegisterType<ICompany, MyCompany>();  
  var myCompany = unitycontainer.Resolve<ICompany>();  

I would rather do the registration in configuration like

  <unity xmlns="">
    <namespace name="InterfaceAssembly.NameSpace" />
    <namespace name="MyAssembly.MyNameSpace" />
      <register type="ICompany" mapTo="MyCompany">
        <constructor />

and in the code we end up just resolving the types at run-time from the configuration

  var unity = new UnityContainer();
  var myCompany = unity.Resolve<ICompany>();

The obvious benefit is that the code now has no knowledge of our concrete class and will not need a rebuild in case our concrete implementation changes to another assembly or class.


One tip about constructors which is not well documented. In case of classing having multiple constructors and our intention is to instantiate the class with the parameter-less constructor we will need an empty constructor element inside the register element. This will force the parameter-less constructor be instantiated.

      <register type="ICompany" mapTo="MyCompany">
        <constructor />

on the other hand if you need to call the paramterised constructor to invoke the class, we can specify it explicitly like

 <register type="ICompany" mapTo="MyCompany">
      <param name="companyName" value="ABC Corp" />
Updated: September 3, 2015 — 10:41 am

Leave a Reply

Your email address will not be published. Required fields are marked *

PM's Blog © 2018