Unity - how to use multiple mappings for the same type and inject into an object

♀尐吖头ヾ 提交于 2019-12-03 16:39:11

There are two ways you can achieve this:

You can use ParameterOverride's and a two step resolution process...

var tool = container.Resolve<ITool>("ToolB");
var worker = container.Resolve<IWorker>("Worker", 
    new ParameterOverride("tool", tool));

...assuming that the constructor argument on Worker that receives the ITool is called 'tool' (multiple ParameterOverride instances can be passed to Resolve). Any other dependencies (via constructor or property injection) that the named instance of IWorker has should be correctly resolved as well.

Alternatively, why not setup named WorkerA, WorkerB, WorkerC instances that require the specified ITool...

container.RegisterType<ITool, ToolA>("ToolA");
container.RegisterType<ITool, ToolB>("ToolB");
container.RegisterType<ITool, ToolC>("ToolC");
container.RegisterType<IWorker, Worker>("WorkerA", 
    new InjectionConstructor(new ResolvedParameter<ITool>("ToolA")));
container.RegisterType<IWorker, Worker>("WorkerB", 
    new InjectionConstructor(new ResolvedParameter<ITool>("ToolB")));
container.RegisterType<IWorker, Worker>("WorkerC", 
    new InjectionConstructor(new ResolvedParameter<ITool>("ToolC")));

The disadvantage I suppose with the latter approach is that if Worker takes additional constructor parameters you will need to specify them to the InjectionConstructor as well, specified in the same order as the constructor you are expecting Unity to use...

container.RegisterType<IWorker, Worker>("WorkerA", 
    new InjectionConstructor(typeof(SomeDependency), new ResolvedParameter<ITool>("ToolA"), typeof(SomeOtherDependency));

However, Unity will lookup the non-named instance of SomeDependency and SomeOtherDependency in the above example, so that saves you a bit of work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!