This is a bad or good design question.
I find it extreme convenient to always inject the complete Unity container in my modules.
1.) You never know, what resources you will need. 2.) The class constructor never needs to be changed, if you need more resources of the container.
This looks like this:
public class ServiceLocator: IServiceLocator
{
private IUnityContainer _container = null;
public ServiceLocator(IUnityContainer container)
{
_container = container;
}
public void DoSomething()
{
var x = this._container.Resolve<IXInterface>();
var y = this._container.Resolve<IYInterface>();
x.Do();
y.Do();
}
}
In tutorials and unity examples, I often see, that you only should inject the resources, that you really need. That looks like this:
public class ServiceLocator: IServiceLocator
{
private XInterface _x = null;
private YInterface _y = null;
public ServiceLocator(Ixnterface x, IYnterface y)
{
_x = x;
_y = y;
}
public void DoSomething()
{
_x.Do();
_y.Do();
}
}
My questions are:
What do you think is better design?
Why would you only inject explicit Interfaces, when the Unity container has all resources in it?
What are the problems in the future?
The only problem I see for the future is, that you ALWAYS have to have a Unity container in the future and if you don't have it, you have to rewrite the module.
What do you think?
EDIT: Some of the best answers I have found is, that the first version is not dependency injection, it is some kind of "Service Locator Pattern", which can cause many problems.
It can be found here:
http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/