如何使用StructureMap指定要注入控制器的命名服务实例

时间:2016-01-15 15:53:31

标签: c# dependency-injection structuremap asp.net-core

Microsoft Unity DI提供了一项功能,您可以在该功能中为同一界面注册多个对象并为其命名。然后在构造函数中,您可以使用带参数的属性来按名称指定要注入的对象。

我想知道如何使用StructureMap实现相同的功能。

示例:

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;
    }
}

0 个答案:

没有答案