Saturday, 10 August 2013

Why Dependency Injection and how to implement , a Ninject Example

Dependency injection is a design pattern that allows the removal of hard-coded dependencies and makes it possible to change them, whether at run-time or compile-time.
It injects the depended-on element (object or value, etc.) to the destination automatically by knowing the requirement of the destination i.e. in simple words we have to register all dependend-on entities seperately as a set , and any time when we need dependent on entity we get that from our collection e.g IService an interface and MyService is a class which has implementation of IService , lets say any where we use IService's method so we have to need MyService which is dependent on in this case and we need it.There are number of 3rd party libraries for injection of dependency , most popular are Autofac, Ninject and Unity.

Why to use :
  • Flexibility to use alternative implementation without recompiling the application code.
  • Loose coupling which promotes use of interfaces.
  • Code becomes more usable, readable and testable.

I do commonly prefer ninject because it is simpler. To download Ninject latest version just run 
Install-Package Ninject -Pre from Package manager console of visual studio.

Now lets see how to implement dependency injection using Ninject , it is very simple , only three steps required.

1) Create a class as dependency resolver 

 public class NinjetDependencyResolver : IDependencyResolver
        private readonly IKernel _container;

        public NinjetDependencyResolver(IKernel container)
            _container = container;

        public object GetService(Type serviceType)

            return _container.TryGet(serviceType, new IParameter[0]);

        public IEnumerable<object> GetServices(Type serviceType)

            return _container.GetAll(serviceType, new IParameter[0]);


2) In second step create a method in Global.ascx , where define your dependencies and use above class as  resolver for those dependencies :

 public void RegisterNinjectResolver()
            var container = new StandardKernel();
            container.Bind<IUserRepository>().To<UserRepository>(); // our dependency
            DependencyResolver.SetResolver(new NinjetDependencyResolver(container)); // our dependency resolver

3) Third and last step is to call method created in second step in App_Start method of Global.ascx 

protected void Application_Start()
            RegisterNinjectResolver(); // here it is


That is all about how to implement DI pattern in your mvc applications, you can download sample project here : DOWNLOAD