What is Dependency Injection

So simple dictionary meaning of dependency is that someone or something has some dependency on another. It means, someone or something is unable to proceed without another one or another thing.

If you join a software company, the company must provide laptop to you proceed your work, the internet must be provided to you. Without having these things you can not proceed, correct ?

If you take an example of car or bike, it depends on fuel, without fuel they can’t proceed.

So In order to proceed something, some other thing must be provided by someone.

In the same way, in programming, some class object or some variable values must be provided to some other class or function in order to proceed some functionality.

Dependency in Programming : Implementation with C#

Let’s take programming example in C#.

Let’s suppose i have a function to sum two number

public int Sum(int a, int b){
   return a+b;
}

We can say that the sum function is depend on two variable values to proceed it’s functionality.

Let’s take another complex example:

Let’s say that i have web-api application, and i want my application to keep track of errors or exceptions occurred in application while it is running.

we generally use to write following code:

public class CustomerController : ApiController
{

    [HttpGet]
    public IActionResult GetCustomers()
    {
       try  
       {
          .... code here for database call to get customers
       }
       catch(Exception ex)
       {
          Logger logger = new Logger();
          logger.Error("Error occurred while calling    
                    GetCustomer() method. Error is:"+ ex.Message)
       }
    }
}

Above method is trying to get customers from database. but suppose some exception happened for whatever reason, catch block is trying to log the error for troubleshooting purpose.

This API call looks perfect, but there is a violation of SOLID principle. and that is : “S” : Single Responsibility principle. So single responsibility principle says: “A class or function should have single responsibility”. As per the name of method “GetCustomers” says “I am responsible for only getting the customers from somewhere, but i am not responsible for creating or initializing any object. Yes, i will of course log errors if there are any, if you provide me those object which are already been initialized.

It is same thing as the earlier example where you join a software company and ask your company to provide you a laptop, internet and other required things to proceed your work. You are responsible for performing a specific role for which you have been hired. Correct ?

In the same way when a class or function is created with some specific name, then it is only limited to perform only those specific functionality.

so the let’s modify the above code:

public class CustomerController : ApiController
{

    [HttpGet]
    public IActionResult GetCustomers(Logger logger)
    {
       try  
       {
          .... code here for database call to get customers
       }
       catch(Exception ex)
       {
         logger.Error("Error occurred while calling    
                       GetCustomer() method. The Error is:"+ ex.Message)
       }
    }
}

Now above code obeys the “S” principle from SOLID principle. “GetCustomer” method is now only responsible for getting customer data from somewhere. Because whoever is calling the “GetCustomer” method, is passing the required dependency(that is logger object) in a function argument.

But let’s suppose if there are 100s of APIs in “CustomerController”, then every api method should get dependency in a parameter. So to avoid this complexity, .NET Core provides facility of injecting the dependencies into constructor of the class as follows:

public class CustomerController : ApiController
{
    private Logger logger;

    public CustomerController(Logger _logger)
    {
        logger = _logger;
    }

    [HttpGet]
    public IActionResult GetCustomers()
    {
       try  
       {
          .... code here for database call to get customers
       }
       catch(Exception ex)
       {
         logger.Error("Error occurred while calling    
                       GetCustomer() method. The Error is:"+ ex.Message)
       }
    }
    [HttpGet]
    public IActionResult GetCustomerById(int customerId)
    {
       try  
       {
          .... code here for database call to get customer by CustomerId
       }
       catch(Exception ex)
       {
         logger.Error("Error occurred while calling    
                       GetCustomerById() method. The Error is:"+ ex.Message)
       }
    }
    
}

Now above code “CustomerController” is getting injected with Logger object when the controller is initialized, so that each and every api method doesn’t need have a parameter with the Logger object. All api methods can use logger object which is initialized from constructor.

In order to to inject any dependencies into constructor of class, you have to register your dependencies (in this case dependency is Logger object) in ConfigureServices method of startup class of .NET Core project.

In this blog i have tried to explain the basic fundamentals of Dependency injection that why we use it.

In order to know more about different dependency level you can read here:

https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection#service-lifetimes

http://www.newsvoop.com

By Deesha

Leave a Reply

Your email address will not be published. Required fields are marked *