views:

411

answers:

1

I'm working with StructureMap for my IoC needs.

To make things pleasantly testable, I'm passing IContainer instances around wherever possible, usually as constructor parameters. As a convenience, I'd like to be able to fall back to using ObjectFactory for a parameterless constructor.

The simplest way (I thought) to do this would be to simply get the IContainer the ObjectFactory class wraps and pass that to the other constructor. Unfortunately, I can't find anywhere this instance is publicly exposed.

The question is:

Is there a way to get the IContainer within ObjectFactory so I can handle it as simply as a user-supplied instance?

Alternatively, is there a way to duplicate the configuration of the ObjectFactory into a new Container instance?

Example:

I would like to be able to do the following:

public class MyClass
{
    public MyClass()
    {
        Container = ... // The ObjectFactory container instance.
    }

    public MyClass(IContainer container)
    {
        Container = container;
    }

    public IContainer Container { get; private set; }
}
+3  A: 

ObjectFactory exposes a Container property which gives you the IContainer you are looking for.

Anytime you need an IContainer (which should not be often) you can always take a dependency on it in your class ctor.

public class INeedAContainer
{
    private readonly IContainer _container;

    public INeedAContainer(IContainer container)
    {
        _container = container;
    }

    // do stuff
}

I do not think there is a way to clone an IContainer. There is a container.GetNestedContainer() method which allows you to keep your transients the same for the lifetime of the nested container. Nested containers are often used within a "using" statement and are very handy for controlling the state of things like database transaction boundaries.

KevM
I'm not sure if that provides me an answer. I've updated my question to clarify the scenario.
Programming Hero
Thanks for the updated answer. I pawed over `ObjectFactory` and didn't find any `Container` property. After your answer said there should be one, I updated to the latest version and violla! Thanks.
Programming Hero