Can someone explain to me the advantages of using an IOC container over simply hardcoding the default implementation into a default constructor?
In other words, what is wrong about this code?
public class MyClass
{
private IMyInterface _myInterface;
public MyClass()
{
_myInterface = new DefaultMyInterface();
}
public MyClass(IMyInterface myInterface)
{
_myInterface = myInterface;
}
}
As far as I can tell, this class supports constructor injection enough so unit testing and mocking is easily done. In addition to which, the default constructor removes the computational overhead of the IOC container (not to mention the whole process is a lot more transparent).
The only benefits i can see to using an IOC container is if you need to switch out the implementation of your interfaces frequently. Am I missing something?
The idea of IoC is to delegate part of your component's functionality to another part of the system. In IoC world, you have components that don't know about each other. Your example violates this, as you're creating tight coupling between MyClass and some implementation of IMyInterface. The main idea is that your component has no knowledge about how it will be used. In your example, your component makes some assumptions about its use.
Actually this approach can work, but mixing IoC and explicit object initialization is not a good practice IMO.
IoC gives you loose coupling by performing late binding for the price of code clarity. When you add additional behavior to this process, it makes things even more complicated and can lead to bugs when some components can potentially receive object with unwanted or unpredicted behavior.