Thursday, 27 March 2014

Dependency Injection in MVC4

Dependency Injection is a design pattern that helps to reduce tight coupling between software components.
Due to loosely coupled code, we can develop maintainable software systems. Dependency Injection pattern uses an object to initialize the objects and provide the required dependencies to object it allows you to inject a dependency, from outside the class.



DI provides objects that an object needs. So rather than the dependencies construct themselves they are injected by some external means. For instance let’s say we have the following below class “Customer” who uses a “Logger” class to log errors. So rather than creating the “Logger” from within the class, you can inject the same via a constructor as shown in the below code snippet.

 public class Customer
    {
        public Logger Log;
        public Customer(Logger obj)
        {
            Log = obj;
        }

    }

Now we can invoke the customer object with any kind of logger.

Customer obj = new Customer (new EmailLogger());
Customer obj1=new Customer (new EventViewerLogger());

 This approach helps in decoupling. Hence dependency injection helps us in developing testable, maintainable and decoupled software components. There are various tools available for implementing depency injection like Ninject, Unity etc. 



No comments:

Post a Comment