Pages

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

23 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
  11. Thats what I was looking for. Simple example and easy to understand. Once I know what DI is made for I can go forward with some more details. Thanks a lot!

    ReplyDelete
  12. Thats what I was looking for. Simple example and easy to understand. Once I know what DI is made for I can go forward with some more details. Thanks a lot!

    ReplyDelete
  13. Easy And Best Way.
    Thanks alot...

    ReplyDelete
  14. Good.. Many post i showed but from this blog i am able to understand how we can implement DI concept in development enviroment

    ReplyDelete