Storing and Retrieving Containers

Feb 22, 2008 at 12:42 AM
Every example that I've found in the Unity documentation starts by creating a new instance of the UnityContainer

IUnityContainer myContainer = new UnityContainer();

followed by configuring the container and then calling Get or BuildUp to retrieve and inject your object instances. This works great if everything I want built by the container can be created and injected at creation time, so I only need the container when I create the initial root object, like the WinForm.

However, In my case I would like to create objects within the returned instances after the creation process is finished. So, for example, say I have something like this

class ForestRenderer
{
public void Draw(ICollection<Tree> trees)
{
foreach (Tree tree in trees)
{
// The container returns a renderer with the base class of TreeRenderer but specific
// to this variety of tree.
TreeRenderer renderer = container.Get<TreeRenderer>(tree.Variety);
renderer.Draw(tree);
}
}
}

Now say that I want all renderer classes in general (not just tree renderers) to share a graphics context singleton, so I'd like them to all be built up by the same container. How do I get access to the container outside of the context where I initially created it? Am I trying to use Unity to do something it's not meant to do?
Feb 22, 2008 at 1:58 AM
Just so I understand correctly, are you asking how to access the container from the ForestRenderer in your example?

If so, then you're telling that ForestRenderer has a dependency on the unity container; hence, it should also be injected. In order to to so, just register the container into itself.

public static void Main()
{
  IUnityContainer container = new UnitContainer();
  container.RegisterInstance<IUnityContainer>(container);
  Application.Run(container.Get<MainForm>());
}
 
public class ForestRenderer
{
  private IUnityContainer container;
 
  public ForestRenderer(IUnityContainer container)
  {
    this.container = container;
  }
 
  public void Draw(...) 
  {
    ...
    container.Get<TreeRenderer>(...) 
    ...
  }
}

Is that what you are looking for?
Feb 22, 2008 at 6:17 PM
Yes it is, thank you very much. The idea to register the container with itself seems to be the piece of the puzzle I managed to overlook.
Apr 22, 2008 at 9:31 AM
PicoContainer documentation says that its antipattern.

http://www.picocontainer.org/container-dependency-antipattern.html