10 Jun 2017

Explain Dependency injection in Asp.net MVC with working example

Explain Dependency injection in MVC with working example

Dependency Injection is a way to achieve Inversion of Control, meaning that your code no longer depends on concrete implementations of different objects, it relies on a decoupled interface which is then bound to a specific implementation.

Take the below code for example;

   public Class FooBar
   {
        public void Foo()
        {

        ExampleClass EC = new ExampleClass();

        EC.DoSomething();

        }
   }


There's nothing technically incorrect with that code, it will compile and run absolutely fine!

But this now means that for your FooBar Class to work, it depends on ExampleClass working properly.

With Dependency Injection, you might have an interface as below;

public Interface IFoobarable
{

void DoSomething();

}

And choose to implement it in your ExampleClass like this;

    public class ExampleClass : IFooBarable
    {

        public void DoSomething()
        {
            //Logic goes here
        }
    }



What that means, is that you can now use the Interface in order to use the methods you want, but the interface now chooses which class to use based on what implements that interface, like so;

    public Class FooBar
    {
        private readonly IFooBarable _ExampleClass;

        public FooBar(IFooBarable ExampleClass)
        {
        this._ExampleClass=ExampleClass;
        }

        public void Foo()
        {

        _ExampleClass.DoSomething();

        }
    }



you only depend on your interface, and not any concrete implementations that may/may not change, all your code needs to know now is what that interface is looking to implement, and leaves your constructor to inject that dependency, if you use Ninject, you can set those bindings in a separate binding module if you have a lot of dependencies to inject 

No comments:

Post a Comment