Monday, March 23, 2015

C# Dependency Injection Simple Example



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
*******************

18 comments:

  1. Simply awesome best example i have ever searched. Keep up

    ReplyDelete
  2. Best and to the point. Simplicity at its best. It took me 5 minutes to understand Constructor DI.

    ReplyDelete
  3. Simply the best. Thank you very much!

    ReplyDelete
  4. You can Change Title to 'How to learn DI in 5mins'. Simply great...

    ReplyDelete
  5. Cooooool! Thank you!

    ReplyDelete
  6. Really easy to understand. Thanks!

    ReplyDelete
  7. Thanks for this crispy article. Helpful !

    ReplyDelete
  8. Nice Explanation. But can you explain this using Unity Application Block?

    ReplyDelete
  9. Lost a lot of time around the net and did not understand how DI works, and then you manage to explain it in such a simple way...
    thank you very much!

    ReplyDelete
  10. Thank you.it very simple to understand DI

    ReplyDelete