Specifying Injection Constructor using Unity Fluent Interface for Loose Coupling and POCO

Each dependency injection framework has its own way of determining the default constructor it will use to create a type. Some will use a parameterless constructor by default, some will choose the greediest constructor, and some will choose the greediest constructor it can fill based on dependencies loaded into the container. I am sure there are others :) In some cases, you can even add various pluggable strategies to determine the behavior.


By default, Unity will choose the greediest constructor. However, there are times when that is not what you want, so you need to give Unity a hint. You can specify the injection constructor either in XML, using an InjectionConstructor Attribute, or via the fluent interface. I will show you via the InjectionConstructor Attribute and Fluent Interface and leave the XML to you :) Note that for those passionate about not letting infrastructure code into your domain model, you want to avoid the attribute method and focus on the Fluent Interface or XML. This will keep any Unity-specific Coupling away from your domain model.


 


InjectionConstructor Attribute


This is by far the easiest way to specify which constructor you want Unity to use to create the type. Notice on the default ( ie parameterless ) constructor how I have added [InjectionConstructor]. This tells Unity to use that constructor. If I remove the [InjectionConstructor] Attribute, Unity will throw an exception. This is because it will choose the greediest constructor by default and I have not added the ICustomerDataSource dependency to the container.


 



using Microsoft.Practices.Unity;


 


namespace UnityPOCO


{


    internal class Program


    {


        private static void Main(string[] args)


        {


            IUnityContainer container = new UnityContainer();


            container.RegisterType<ICustomerRepository, CustomerRepository>();


 


            var repository = container.Resolve<ICustomerRepository>();


        }


    }


 


    public interface ICustomerRepository {}


 


    public class CustomerRepository : ICustomerRepository


    {


        private readonly ICustomerDataSource _dataSource;


 


        [InjectionConstructor]


        public CustomerRepository() : this(new CustomerDataSource()) {}


 


        public CustomerRepository(ICustomerDataSource dataSource)


        {


            _dataSource = dataSource;


        }


    }


 


    public interface ICustomerDataSource {}


 


    public class CustomerDataSource : ICustomerDataSource {}


}


 


The only issue ( which could be minor or big depending on your viewpoint ) is that now my CustomerRepository Class has a coupling to Unity due to the [InjectionConstructor] Attribute. Let’s remove that dependency.


 


Unity Fluent Interface


Let’s specify the default ( parameterless ) constructor as the injection constructor via the fluent interface as opposed to an attribute as such:


 



using Microsoft.Practices.Unity;


 


namespace UnityPOCO


{


    internal class Program


    {


        private static void Main(string[] args)


        {


            IUnityContainer container = new UnityContainer();


            container.RegisterType<ICustomerRepository, CustomerRepository>().Configure<InjectedMembers>().


                ConfigureInjectionFor<CustomerRepository>(new InjectionConstructor());


 


            var repository = container.Resolve<ICustomerRepository>();


        }


    }


 


    public interface ICustomerRepository {}


 


    public class CustomerRepository : ICustomerRepository


    {


        private readonly ICustomerDataSource _dataSource;


 


        public CustomerRepository() : this(new CustomerDataSource()) {}


 


        public CustomerRepository(ICustomerDataSource dataSource)


        {


            _dataSource = dataSource;


        }


    }


 


    public interface ICustomerDataSource {}


 


    public class CustomerDataSource : ICustomerDataSource {}


}


 


I removed the [InjectionConstructor] Attribute and now specify the constructor by configuring the InjectedMembers for CustomerRepository during registration. The code, new InjectionConstructor(), is the same as saying the default, parameterless constuctor is now the Injection Constructor. The code works as expected and you will notice that the class is not coupled to Unity anymore.


If you ever decide Unity is not for you, you are now free to move to the Inversion of Control ( IoC ) Container of your choice. This is a good thing. The less dependencies the better.


 


Conclusion


I tend to be fairly opinionated on how I register types to keep things simple and consistent. I recommend looking at extending Unity with Extension Methods in C# 3.0 to simplify a lot of your type registrations. You can check out any of my other Unity Tutorials as well as some new posts on the new Interception Extension in v1.2 with support for TransparentProxyInterceptor, VirtualMethodInterceptor, and InterfaceInterceptor.


 


Hope this helps,


David Hayden


 


Recent Posts



 

This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

One Response to Specifying Injection Constructor using Unity Fluent Interface for Loose Coupling and POCO

  1. With the release of Unity 1.2, there is a better API to do this. You can do:

    container.RegisterType(new InjectionConstructor());

    Could you please start using this in your examples instead of the older ConfigureInjectionFor call?

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>