Dependency Injection Confusion

Posted by James on Programmers See other posts from Programmers or by James
Published on 2013-06-29T08:48:14Z Indexed on 2013/06/29 10:28 UTC
Read the original article Hit count: 282

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.

© Programmers or respective owner

Related posts about c#

Related posts about design-patterns