Sunday, 6 March 2016

Dependency Injection in C# with Example




Dependency Injection (DI) is a design pattern that take away from the responsibility by creating a dependency class to create  loosely coupled system.Most people not clear idea about what is dependency injection (DI) and when it want to use in the code.

In this article i'm taring to describe what is dependency Injection(DI) and how we use to get loosely coupled system using simple example.Imagine you have face situation like follow


you have class Employee and it has Logger for print message.and also you have to add another Logger method for different customer,normally we can implement that as follow.

public class Employee
{
    private LoggerOne LoggerOne;
    private LoggerTwo LoggerTwo;

}

public class LoggerOne
{
    public void WriteToLog(string text)
    {
        Console.WriteLine(text);
    }
}

public class LoggerTwo
{
    public void WriteToLog(string text)
    {
        Console.WriteLine("***********\n {0}\n***********",text);
    }
}

 but in this implementation Employee class tightly coupled with  LoggerOne and LoggerTwo.So this system hard to modify and reuse.

So prevent that issue we can use dependency Injection to solve this and get loosely coupled system.

  
We can use interface ILogger class for the Logger to inject the dependency to Employee class as follow

public class Employee
{
    private ReadOnly ILogger _logger;
    public Employee(ILogger Logger){
 
       _logger=Logger;
       _logger.WriteToLog("Test Logger");
    }

}

public interface ILogger
{
    void WriteToLog(string text);
}

public class LoggerOne : ILogger
{
    public void WriteToLog(string text)
    {
        Console.WriteLine(text);
    }
}

public class LoggerTwo : ILogger
{
    public void WriteToLog(string text)
    {
        Console.WriteLine("***********\n {0}\n***********", text);
    }
}
Now let's instantiate an Employee with two different loggers:

 Employee employee1 = new Employee(new LoggerOne());
 Employee employee2 = new Employee(new LoggerTwo());

 And the output:

 Test Logger

*******************
Test Logger
******************

No comments:

Post a Comment

Single Responsibility Principle (SRP)