Search This Blog

Friday 11 December 2015

Dependency Injection

People are often confused about what Dependency Injection is and when they might need or want to use it. Some time ago I wrote an article Managing Dependency Injection in C# with Autofac which explains how to manage DI in C#, but today I want to show by simple code sample what actually Dependency Injection is.
Imaging situation where you have a class, let's say Employee, and two or more different loggers for that class. Each logger prints messages in his own particular way and you want to have control of which logger to use for Employee during its instantiation.
Just take a look at this code and I'm sure you will get the idea of Dependency Injection:

public class Employee
{
    public Employee(ILogger logger)
    {
        logger.WriteToLog("New employee created");
    }
}
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:
New employee created
*******************
New employee created
*******************

The advantages of using Dependency Injection pattern and Inversion of Control are the following:

•Reduces class coupling

•Increases code reusing

•Improves code maintainability

•Improves application testing

No comments:

Post a Comment