Remove Child Containers

Sep 26, 2008 at 7:03 PM

I have situation where I have a hierachy of containers and a few possible scenarios arise.

  1.     The last container in the hierachy needs to be removed and then attached to a new parent.
  2.     A container in the middle of the hierachy needs to be removed.

What is the best way to achieve this behavior.  I don't mind even having to rebuild the containers, but how is that possible (i.e. perserving all type regs).

Thanks in advance,


Sep 26, 2008 at 7:24 PM
Basically, you don't. Creating a child container is a one-shot operation, and there's no way to reparent a container.

If I may ask, what is your scenario & design for using child containers? Obviously you're doing something differently than I anticipated when I designed the feature and I'd like to know more about what you're trying to do.

Sep 26, 2008 at 7:35 PM

This is dealing with a scopable MVC pattern.

Basically, we create a root scope that house basic controllers (i.e. Close, ExitApp, About, misc Services, etc..).

Then when a specific feature is accessed a new "child" scope is created.  In this scope some controllers may be overriden by registering another type reg in the child container (e.g. replacing the closing controller or something).

This goes further with nested scopes being created again for nested views and popups.

Now the need for removing or more aptly switching parents is this.  Say I launch a child scope in my shell window.  This scope would be a child of the shell's scope.

Now if I want a feature where I can detach this child view and then reattach it to another window, which of course will have it's on scope with different registrations, I would need to reparent this child container.

I also must say I have a hack that seems to be working, but it doesn't feel right, and I would like some feedback as to what downsides this may have.

I did this by modifiying the UnityContainer source to include this method:

/// Enables a container to switch or drop a parent container
/// </summary>
/// <param name="parentNew">New parent or null if no parent is desired.</param>
public void SwitchParent(UnityContainer parentNew)
    if (parent != null && parent.lifetimeContainer != null)



    this.parent = parentNew;



    if (parent != null && parent.lifetimeContainer != null)


    registeredNames =

new NamedTypesRegistry(ParentNameRegistry);
    //extensions = new List<UnityContainerExtension>();
locator = new Locator(ParentLocator);
    //lifetimeContainer = new LifetimeContainer();
    strategies = new StagedStrategyChain<UnityBuildStage>(ParentStrategies);
    buildPlanStrategies =
new StagedStrategyChain<UnityBuildStage>(ParentBuildPlanStrategies);
    policies =
new PolicyList(ParentPolicies);