0

Microsoft Unity DI offers a feature where you can register multiple objects for the same interface and give them a name. Then in your constructor you can use an attribute with the argument to specify by name which object you want to inject.

I am wondering how to achieve this same functionality using StructureMap.

Example:

container
.RegisterType<IMappingEngine, MappingEngine>("MappingEngineOne", new HierarchicalLifetimeManager(), new InjectionConstructor(typeof(MappingEngineOneConfiguration)))
.RegisterType<IMappingEngine, MappingEngine>("MappingEngineTwo", new HierarchicalLifetimeManager(), new InjectionConstructor(typeof(MappingEngineTwoConfiguration)))

....

public class MyServiceAgent {
    private readonly IMappingEngine _mapper;
    public MyServiceAgent([Dependency("MappingEngineOne")] IMappingEngine mapper) {
        _mapper = mapper;
    }
}

public class MyOtherServiceAgent {
    private readonly IMappingEngine _mapper;
    public MyOtherServiceAgent ([Dependency("MappingEngineTwo")] IMappingEngine mapper) {
        _mapper = mapper;
    }
}
Chris Putnam
  • 884
  • 1
  • 10
  • 16
  • Why do you need to do this? This is a bad practice. Your classes should not know about which implementations they should receive. – Yacoub Massad Jan 15 '16 at 16:56
  • We have multiple services that need an IMappingEngine instance instantiated with a certain configuration. How would you go about solving this? – Chris Putnam Jan 15 '16 at 18:24
  • Have a look at [this question](http://stackoverflow.com/questions/34649735/dynamic-selection-of-interface-implementation-using-ioc). – NightOwl888 Jan 15 '16 at 20:50

0 Answers0