views:

80

answers:

1

I know that I can specify a constructor to use with the DefaultConstructor attribute. However, I also want to be able to use a different constructor in some instances. Is there any way I can register both constructors with StructureMap, and then choose which one to use when I call ObjectFactory.GetInstance()?

+1  A: 

I do not believe you can do that in StructureMap. Can you pull the separate constructor behaviors you are looking for out into an adapter class. Then your code can take dependencies on the necessary adapter class.

    public class FirstBehavior : IBehavior
{
    private WrappedClass _wrappedClass;
    public FirstBehavior()
    {
        _wrappedClass = new WrappedClass(<first constructor>)
    }
}

public class SecondBehavior : IBehavior
{
    private WrappedClass _wrappedClass;
    public SecondBehavior()
    {
        _wrappedClass = new WrappedClass(<second constructor>)
    }
}

[TestFixture]
public class Test
{
    [Test]
    public void configure_container()
    {
        var container = new Container(config =>
        {
            config.For<IBehavior>().Use<FirstBehavior>().Named("first");
            config.For<IBehavior>().Use<SecondBehavior>().Named("second");
        });

        container.GetInstance<IBehavior>("first").ShouldBeOfType(typeof(FirstBehavior));
        container.GetInstance<IBehavior>("second").ShouldBeOfType(typeof(SecondBehavior));
    }
}
KevM