0
votes

I want to be able to retrieve all instances of a particular interface which have been configured in Structuremap under a given name.

I'm already using Structuremap within the project for constructor injection and it seems like the kind of thing I ought to be able to accomplish with it.

For example: I have an interface IProcessor which many concrete classes implement. Each concrete class has a name, with some classes sharing the same name. For a given name I want to be able to return all concrete instances of IProcessor.

IEnumerable<IProcessor> processors = ProcessorsByName("foo");

ProcessorsByName(string name)
{
    // Some Structuremap magic here
    // Ideally something like (which I know doesn't exist)
    return ObjectFactory.GetAllNamedInstances<IProcessor>(name);
}

I know that I could call ObjectFactory.GetAllInstances<IProcessor>() and then enumerate through that testing each one to see if it's the right name, but that sounds wasteful.

// Possible solution
interface IProcessor
{
    string Name { get; }
}

IEnumerable<IProcessor> processors = ProcessorsByName("foo");

ProcessorsByName(string name)
{
    // Having a dog and barking yourself
    return ObjectFactory.GetAllInstances<IProcessor>().Where(p => p.Name == name);
}
1
StructureMap does not support multiple instances with the same name. You will have to implement your own mechanism on top of it. Your proposed solution would work fine if you need to group instances by name. If you describe the problem you are trying to solve, there may be other solutions aside from grouping by name. - Joshua Flanagan

1 Answers

0
votes

One way:

public sealed class MyRegistry : Registry
{
    public MyRegistry()
        : base()
    {

        For<IProcessor>()
            .Use<FooProcessor>().Named("Foo");