views:

355

answers:

1

Hi there,

I am pretty new to the Unity Application Block and am a little stuck trying to implement the following. I have a parent and child container. When i resolve a new instance of the child container i want to inject a new UnityContainer into the constructor using the CreateChildContainer method.

public class RootContainer
{
    private IUnityContainer _container;

    public RootContainer()
    {
        _container = new UnityContainer();
        _container.RegisterType<IChildContainer, ChildContainer>();
    }
}

public interface IChildContainer { }

public class ChildContainer : IChildContainer
{
    private IUnityContainer _container;

    /* I want to inject the parent.CreateChildContainer() into this constructor */
    public ChildContainer(IUnityContainer container)
    {
        _container = container;
    }
}
A: 

The simplest solution I see is to give the ChildContainer's constructor the parent container and call the CreateChildContainer() method within the ctor:

public class ChildContainer2 : IChildContainer
{
    private IUnityContainer _container;

    public ChildContainer(IUnityContainer parent)
    {
        _container = parent.CreateChildContainer();
    }

    public IUnityContainer Container { get { return _container; } }
}

But why do you want to make the child container a service? Wouldn't it be better if each component in your app would create a child container by itself if it needs one?

Prensen
I guess you are assuming the following.. public RootContainer() { _container = new UnityContainer(); _container.RegisterInstance<IUnityContainer>(_container); _container.RegisterType<IChildContainer, ChildContainer>(); }
Nigel Thorne