문제

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

thanks.

도움이 되었습니까?

해결책 2

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top