Question

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.

Was it helpful?

Solution 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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top