开发者

StructureMap IOC named instances help

Having a problem with StructureMap IOC. I wish to retrieve different concrete implementations of objects that implement the same interface based on labels or names.

internal static class InstanceHelper
{

    internal enum Taxonomy
    {
        Foo,
        Bar
    }

    static InstanceHelper()
    {
            // Initialize the container
            ObjectFactory.Initialize(x =>
            {
                x.For<IMyInterface>().Use<ObjectA>().Named(Taxonomy.Foo.ToString());
                x.For<IMyInterface>().Use<ObjectB>().Named(Taxonomy.Bar.ToString());
            });

    }

    internal static IMyInterface GetInstanceByTaxonomy(Taxonomy taxonomy)
    {

          // this raises an exception
          ObjectFactory.GetNamedInstance<IMyInterface>(taxonomy.ToString());

    }
}

Documentation is not to good in this regard, seems like all the examples out there are deprecated... using version 2.6.1.0

tha开发者_StackOverflow社区nks.


Thy using the AddInstances method to add your named instances

ObjectFactory.Initialize(x =>
{
    x.For<IMyInterface>().AddInstances(i =>
    {
        i.Type<ObjectA>().Named("Foo");
        i.Type<ObjectB>().Named("Bar");
    });
});

This works for me, however I do agree the documentation can sometimes be quite misleading between versions and it took me a while to get to this the first time around.


Both the original way and amarsuperstar's way appears to actually work, the problem was that the scope of class 'ObjectA' had been declared as internal, along with an internal constructor. I changed this to Public and now IOC can see it... inverse reflection is happening within the StructureMap assembly. Doh silly me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜