Classic dependency injection

With dependency injection, only interfaces are exposed to method callers, which means, details of the method is protected and invisible when being referened, in addition, the interface can be extended as customized and then let same method supports more similar cases.

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 initialize 2 Employee with two different loggers:

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

Output:

New employee created

*******************
New employee created
*******************

Reference: www.codearsenal.net/2015/03/c-sharp-dependency-injection-simple.html

Leave a Reply

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