3

Possible Duplicate:
Inversion of Control < Dependency Injection

Could anyone please help me to understand DI and IOC with simple C# example please? As I understand IOC is the inversion of control flow (which means nothing to me) and DI means injecting interfaces via properties or constructors. Not sure how these two are related.

Thank you.

Community
  • 1
  • 1
Nil Pun
  • 17,035
  • 39
  • 172
  • 294

4 Answers4

6

Let's say you have a class that needs a service:

public class A 
{
  IEmailSender _emailSender
  public A(IEmailSender emailSender)
  {
    _emailSender = emailSender;
  }

  private void SendEmail()
  { 
    _emailSender.Send();
  }
}

Class A now is said to has a dependency on IEMailSender, meaning it needs an object that implements IEMailSender to be able to perform it's function.

A dependency injection framework like ninject or autofac would be responsible for creating an object that implements IEMailSender and injecting it into the constructor of A, provided that you told them how to create such object.

Ex using ninject:

Bind<IEmailSender>().To<EmailSender>();

this is telling ninject, whenever a class needs an IEMailSender, give them EmailSender (assuming ofcourse that EmailSender implements the IEMailSender interface)

This is as simple as I can think of, hope this helps.

Bassam Mehanni
  • 14,796
  • 2
  • 33
  • 41
5

I highly recommend you to read Dependency Injection in .NET book, it in details describes all aspects with comprehensive code examples. For the inversion of control you should refer to another book by Robert Martin: Agile Principles, Patterns, and Practices in C#. It in details describes SOLID principles with examples and understandable explanations. These two books really helped me to understand these principles.

Eugene Cheverda
  • 8,760
  • 2
  • 33
  • 18
  • +1 for SOLID. I interview too many people who can't answer basic questions around those principles. – Ian Feb 09 '12 at 21:36
4

I'll add an explanation that I've been told is a helpful one.

As you correctly point out, dependency injection is the act of a class demanding its collaborators via constructor or setter injection. You could think of this as a coding technique. Inversion of control, on the other hand, is more of a design technique -- a philosophy, if you will.

In procedural programming (and procedural-style programming in OO languages), you generally have some kind of "command and control" philosophy. If you're creating a house object that consists of three floor objects, which consist of some number of room objects each, you create a house object whose constructor instantiates three floor objects, each of whose constructor, in turn, instantiates room objects.

When you invert control, you're inverting command and control paradigm. With IoC, when I go to instantiate a house, it doesn't take care of all of its details for me. Instead, it says, via its constructor (and dependency injection), "you can't instantiate me without some floors". So, you go to instantiate the floors and they say "nope, not without some rooms". Now, in this "inverted" style, our house doesn't control the creation of the rooms - it leaves that up to someone else and it expresses instead, only what it will do with the rooms it's given. This is desirable because, by flipping command and control on its head, you have better seams for reasoning about and testing the code -- it's easier to deconstruct things into components.

So, to summarize, inversion of control is the philosophy and dependency injection is the means by which it's achieved.

Erik Dietrich
  • 6,080
  • 6
  • 26
  • 37
2

DI is IoC. Inversion of Control means swapping who decides how a task is achieved.

In ye old worlde, you might create a class called Logger and a method in that class called LogTime(). It's sole purpose is to write the current time to a file.

public void LogTime()
{
    WriteToFile(GetCurrentTime());
}

Here the class has a method called WriteToFile and GetCurrentTime. IoC simply means that instead of the Logger class deciding how to write to the file, or even get the current time, you can have an outside provider provide those details.

That's where DI comes in. You Inject a dependency. The method is dependent on a means of writing to a file and getting a current time. You inject those methods.

There are two common patterns for DI which are property injection and constructor injection. They do what they say on the tin. The how is up to the particular framework doing the injecting.

Some use attributes, some use config files. Some take a best guess approach.

Along side DI you have SL (Service Location) which is like polite DI. In DI you say "Take this dependency and like it". With SL the Logger class above would say "Would it be possible to have something to fill this dependency please??". See? Polite.

The core to making it work is interfaces. LogToFile may be a method on ILogsToFiles interface. You can then have half a dozen different implementations of that interface and inject the most appropriate.

There are loads of frameworks available that manage all this for you, but a simple ServiceLocator is 10 lines of code, a simple DI probably no more than double that. You'll soon start wanting extra though. Take a look at Ninject. I recommend it purely because it is small and simple and probably a good starting place.

Ian
  • 4,885
  • 4
  • 43
  • 65