Alex Rivera | Logout

Best Practices for IOC Container

Asked 2009-01-26T16:02:33.203
27

I'm using the Unity IOC container and I'm just wondering what is the best best way to access the container for multiple classes.

Should every class have an IUnityContainer member and then pass the container in by constructor? Should there be a singleton class with an IOC container?

How about asp.net development?

Could somebody guide me in the right direction? Thanks.

Edit
Report

2 Answers

6

you can register the container in itself and have it injected like every other dependency property, like so:

IUnityContainer container = new UnityContainer();
container.RegisterInstance<IUnityContainer>(container);

classes that need to access it will have the following property:

private IUnityContainer unityContainer;
[Dependency]
public IUnityContainer UnityContainer
{
    get { return unityContainer; }
    set { unityContainer = value; }
}

thus, the container is injected whenever an instance of such a class is resolved/built up.

This is more flexible as it works for multiple containers within the same application, which would not be possible with the singleton pattern.

answered 2009-01-26T16:25:37.573
2

If all of your objects need a reference to the container then you should look into reworking the code some. While still preferable to calling new everywhere it still scatters the responsibility of building your object graphs throughout your code. With that kind of usage it strikes me as being used more like a ServiceLocator instead of a IoC Container.

answered 2009-01-26T17:19:25.997

Your Answer