I will cover most of the topics about Dependency Injection in this Series. This series contains four parts as follows

Let start with Part 2: Understanding how to implement Dependency Injection using Unity

Before we dig in to real time action with an example, will recall and understand what is dependency injection.

Dependency Injection is a technique to inject the requested object in to other class via. using Constructors or properties. Please read <<Part 1>> to understand more about dependency Injection and how it is useful in complex applications.

Before going to a real time implementation of Dependency Injection, we need to understand following principles

  1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
  2. Abstractions should not depend upon details. Details should depend upon abstractions.

Will do more understanding of these statements with the following real time implementation.

For this implementation we will use Microsoft Unity Framework. Now you might got a question like what is Unity and what can it does here? Well, Unity is the Dependency Injection Framework designed by Microsoft. As we learnt above that Dependency Injection is a Technique and as per this technique some one should create an object at run time and pass this to the requested class. So, Unity Framework will does this for us, it takes all responsibility of creating objects on demand and maintaining these objects in to its container and also it has the feature to manage the life time of these objects based on given configurations or based on requirement, for example, logging object doesn’t need to create for every request or call so the life time of this object can be application life time.

Enough theory now, lets work on implementing this by understanding and following these below steps.

Step-1: Create one ASP.Net WebAPI project. I don’t go to in explaining how to create this project as expecting the readers are well aware of this process using Visual Studio IDE.

Step-2: Go to Nuget package manager (right click on WebAPI project select “Manage Nuget Packages”) and add “Unity” package to our WebAPI project.

Step-3: Once package is installed, our project is ready to work with Dependency Injection as by default core features of DI will be available in System.Web.Http module.

Step-4: Now, we need to create a custom Resolver where we need to provide information to the system how should resolve the requested class objects using Unity Framework, as in market we have many such frameworks and each will resolve requests differently.

This custom resolver class let’s say “UnityResolver” should implement a core interface “System.Web.Http.Dependencies.IDependencyResolver”  as follows

public class UnityResolver : IDependencyResolver 
    { 
        IUnityContainer _container; 
       
        public UnityResolver(IUnityContainer container) 
        { 
            if (container == null) 
            { 
                //TODO: Need to log here 
                throw new ArgumentNullException("container"); 
            } 
  
            _container = container; 
        } 
  
        public object GetService(Type serviceType) 
        { 
            try 
            { 
                return _container.Resolve(serviceType); 
            } 
            catch 
            { 
                return null; 
            } 
        } 
  
        public IEnumerable<object> GetServices(Type serviceType) 
        { 
            try 
            { 
                return _container.ResolveAll(serviceType); 
            } 
            catch 
            { 
                return new List<object>(); 
            } 
        } 
        public IDependencyScope BeginScope() 
        { 
            var childContainer = _container.CreateChildContainer(); 
  
            return new UnityResolver(childContainer); 
        } 
  
        public void Dispose() 
        { 
            _container.Dispose(); 
        } 
    }

As in the above code UnityResolver class is implementing IDependencyResolver interface where this interface will contain following one method declaration and in turn, it inherited with IDependencyScope interface and it contains more two methods as shown below.

public interface IDependencyResolver : IDependencyScope, IDisposable 
    { 
        IDependencyScope BeginScope(); 
    } 
 
    public interface IDependencyScope : IDisposable 
    { 
        object GetService(Type serviceType); 
        IEnumerable<object> GetServices(Type serviceType); 
    }

Now let’s understand these methods

  •  BeginScope(): This method will be called by the runtime for the first time when the application starts and it is responsible for managing all objects.
  • GetService(Type serviceType): This method will be called by the runtime if requires any object of given serviceType. This service type will be sent via. Its parameters and it will get resolved and returns the new or existing object depends on its life time settings.
  • GetServices(Type serviceType): This is also similar to GetService but a runtime will call this method when their is a service type registered with more than one service. This method will return all the service objects which was registered by this given service type.

In the above code we implemented these methods with respective logic based on Unity framework as this framework is pretty simple and their is no much logic to resolve the given service type. Also, we are having a constructor will accept IUnityContainer parameter.

Step-5: In this step we need to inform to our runtime saying, we have created our own custom resolver and please use this resolver as default Dependency Resolver. We can do this in two places either in Global.asax or WebApiConfig class (we are getting this class by default in new version IDE).

IUnityContainer unityContainer = new UnityContainer(); 
unityContainer.RegisterType<IEmployeeBusiness, EmployeeBusiness>(new HierarchicalLifetimeManager()); 
httpConfiguration.DependencyResolver = new UnityResolver(unityContainer);

Let’s understand the above three lines of code, the first line we have created a unity container object where it will be responsible for managing all the objects in its container based on their configured life time. Now, we are ready with container but how could this unity will know about our services? And to which service object should create for which service type?   Exaclty, the second statement doing the same it registering with our Unity Container saying for IEmployeeBusiness request provide EmployeeBusiness class object with life time (these life times will cover in coming parts). Here I provided only one for example in real time we need to register all our services. Unity framework also provides us to register these services via. Xml files such that no need to recompile the application in case if their is any changes in resolving services with this we achieve late binding feature as we discussed in part 1.

Once this custom resolver is ready, the third step informing to the runtime about this custom resolver by providing its object.

That’s it, we are done with setting up DI and now we are ready for real action in next steps.

Step-6: We will create one Controller called EmployeeController and inject this Employee Business object to this controller via. Constructor. 

public class EmployeeController : ApiController 
    { 
        IEmployeeBusiness _employeeBusiness; 
  
        public EmployeeController(IEmployeeBusiness employeeBusiness) 
        { 
            _employeeBusiness = employeeBusiness; 
        } 
    }

Here the runtime will resolve this  IEmployeeBusiness using our custom resolver and provides EmployeeBusiness class object at runtime.

The above implementation is very straight forward and scopes for more customization. In online we will get may built-in components which will perform all these inner things but it will more heavy to the application and also cannot able to customize as you like.

In the next part, we will understand different ways of injecting the dependencies.

Part 3: Understanding different ways of injecting Dependencies