Wednesday 22 April 2009

Unity: Accessing the Creating Container

Here's something I learned today about Microsoft's Unity.

Often when an object is created through a container, you want to be able to access that container so that you can perform further resolutions. In the past my solution to this was to create a static class that held onto a single global instance of the container, essentially a Service Locator. The Service Locator could then be used by any class to access the same container.

I have never been 100% happy with this because, as we all know, static global data is a *bad* thing which introduces dependencies which are hard to test. Today I discovered that when a container resolves a class which has a parameter of type IUnityContainer, the container will pass itself to that parameter. This means that the container can be passed down the chain of constructors without resorting to any global static nonsense.

Here is my test:


[Test]
public void ContainerPassesItselfToObjectsItCreates()
{
var container = new UnityContainer();
container.RegisterType<ClassCreatedByIoC>();

var objectCreatedByIoC =
container.Resolve<ClassCreatedByIoC>();
Assert.That(objectCreatedByIoC.Container,
Is.SameAs(container));
}

public class ClassCreatedByIoC
{
public ClassCreatedByIoC(IUnityContainer container)
{
Container = container;
}

public IUnityContainer Container { get; private set; }
}



I assume this works with injection methods and properties as well, but I haven't tested it.

No comments: