In one of our previous blogs a while back we discussed Dependency Injection and how we can implement this software design pattern in our websites and web projects. We discussed the concept of how we can create loosely coupled modules and inject dependencies amongst them later on during run time or design time using the concept of Inversion of Control through Dependency Injection. However in that Blog we didn't go into detail of how we can achieve this using some existing very powerful libraries out there. We just discussed the concept and I'm sure that some of you were intrigued by the concept and searched around on the web for some existing 'ready to use' libraries. In this blog we will be discussing Microsoft Unity, which is a light weight but powerful dependency injection container.

Most popular .NET Dependency Injection Frameworks

Lets first have a look at some of the most popular Dependency Injection frameworks out there. I've already started experimenting with some of them although so far, I'm still drawn by the simplicity and extensibility of Microsoft Unity. However at Incredible Web we believe that our loyalty should never be toward the License of a particular product but towards the quality it will help us achieve in our websites. Therefore I am going to list down the three most popular Dependency Injection Frameworks apart from Microsoft Unity and feel free to try them out and let us know if you discover any interesting features found in any of the frameworks in the comments section below.

Using Microsoft Unity

One thing I like about Microsoft Unity is that it is quite easy to set up and it is well documented so you will find tons of examples and libraries with extended tools and features. If you've read our blog about Dependency Injection, I explained how with dependency Injection, you can create a declaration of service or a module in terms of Interfaces and them choose which implementation to use for that module at run time or design time (both approaches supported by Microsoft Unity). 

Register Types with Unity

When registering a type with unity, you're just creating a map between the Interface and a potential implementation of that particular interface. There could be more than one possible implementation of an interface. Registration of a type in Unity can be done as follows:

    public class DependencyConfigurations
    {
        public static void ConfigureContainer(IUnityContainer container)
        {
            container
            .RegisterType<ICommentService, CommentService>(new   ContainerControlledLifetimeManager())
        }
    }

 In our projects we find it simpler to create a class which handles all related type registrations called the 'Dependency Configuration' class. What's basically happening here is that we are instructing Unity that whenever an 'ICommentService' is referred to within the project, one possible implementation would be the 'CommentService' class. As of yet we are not 'Resolving' the registration, we are just declaring it.

Resolve with Unity

Resolving a type means asking Unity to create an instance of that particular module in the class where it is being used. Lets say for example we have a Service which is using the CommentService without knowing how or where it will be implemented from. Now in order not to have to call the 'Resolve' method every time a particular Service is making use of a module which will be implemented using Unity, we define what is called a 'UnityControllerFactory'. The Unity Controller Factory will inherit from 'DefaultControllerFactory' as shown below:

 public class UnityControllerFactory : DefaultControllerFactory
    {
        private readonly IUnityContainer _container;
        public UnityControllerFactory(IUnityContainer container)
        {
            _container = container;
        }
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType) { if (controllerType != null) { return _container.Resolve(controllerType) as IController; } return base.GetControllerInstance(requestContext, controllerType); } }

This will instruct the IUnityContainer to resolve the ControllerType and get a Controller Instance every time it is called in a constructor. 

The registration and the configuration of the Unity Container should be done as early as possible in the application's life cycle because Unity will need to know what to inject and how to create the dependencies amongst the various modules. This could possibly be done in the Application_Start method in the Global.asax.cs file. The code below shows  one possible setup of the Unity Container.

 

private static IUnityContainer _container;
override protected void Application_Start(object sender, System.EventArgs e) { base.Application_Start(sender, e); _container = new UnityContainer();
ActaMaltaBusiness.Bootstrap.DependencyConfigurations.ConfigureContainer(_container);
//Set for Controller Factory IControllerFactory controllerFactory = new UnityControllerFactory(_container);
ControllerBuilder.Current.SetControllerFactory(controllerFactory); }

 

Using Unity through Constructor Injection

 All that is left now is to use the services and modules within your controllers or other modules. This would simply be done as shown below:

 public class HomeController : BaseController
{ private ICommentService commentService; public HomeController(ICommentService commentService) { this.commentService = commentService; } public UseCommentService() { commentService.GetAllComments(); } }

 When the GetAllComments() method is invoked, we know from which service it was implemented even though in this particular class no particular instance was called. That's the beauty of Dependency Injection. The Service could have easily been changed to 'CommentServiceTest' durting the registration and nothing else within the code would need to be altered because the HomeController is not making a reference to the specific implementation but to the Interface of the implementation which could be implemented by several candidate services.

 I hope you enjoyed reading this blog and are now eager to try this out yourselves. For more information related to Microsoft Unity please follow this link. The Unity package can be downloaded and installed as a Nuget Package. In future blogs we will go into more detail regarding the container life time managers and other types of dependency injection provided by Unity. 

Until then, thank you for reading.

Shaun