Dependency Injection in C# – Common Confusions Explained

cdependency-injectiondesign-patternsinversion-of-control

I think I have a decent grasp of what Dependency Inversion principle (DIP) is, my confusion is more around dependency injection.

My understanding is the whole point of DI is to decouple parts of an application, to allow changes in one part without effecting another, assuming the interface does not change.

For examples sake, we have this

public class MyClass(IMyInterface interface)
{
   public MyClass
   {
      interface.DoSomething();
   }
}

public interface IMyInterface
{
    void DoSomething();
}

How is this

var iocContainer = new UnityContainer();
iocContainer.Resolve<MyClass>();

better practice than doing this

//if multiple implementations are possible, could use a factory here.

IMyInterface interface = new InterfaceImplementation();
var myClass  = new MyClass(interface);

It may be I am missing a very important point, but I am failing to see what is gained. I am aware that using an IOC container I can easily handle an objects life cycle, which is a +1 but I don't think that is core to what IOC is about.

Edit

Here is an expanded example:

void Main()
{
    IRepository repository = new AddRepository();
    var maths = new PointlessMaths(repository,5);
    Console.WriteLine(maths.Result);
}

public interface IRepository
{
    int DoSomething(int id);    
}

public class AddRepository : IRepository
{
    public int DoSomething(int id)
    {
        return id + 1;
    }
}

public class SubtractRepository : IRepository
{
    public int DoSomething(int id)
    {
        return id - 1;
    }
}

public class PointlessMaths
{
    public int Result {get;set;}
    public PointlessMaths(IRepository repository, int id)
    {
        Result = repository.DoSomething(id);        
    }
}

Best Answer

In your example, you haven't gained anything. Your intuition is correct. If you have only one class implementing an interface, there is no gain, because it may always stay that way. There is no limit to the degree to which we can add interfaces and clutter the code.