I'm using Unity 2.0 and in the following code I'm trying to inject a specific tool in the Worker object.
I would like to use the following code. But ofcourse there is an error "Resolution of the dependency failed". I believe I should be able to do something like this, but I'm having a difficult time figuring it out.
IUnityContainer container = new UnityContainer();
container.RegisterType<IWorker, Worker>("Worker")
.RegisterType<ITool, ToolA>("ToolA")
.RegisterType<ITool, ToolB>("ToolB")
.RegisterType<ITool, ToolC>("ToolC");
IWorker worker = container.Resolve<Worker>("ToolA");
I know this doesn't work, but how would I resolve this issue?
BarDev
There are two ways you can achieve this:
You can use
ParameterOverride's and a two step resolution process......assuming that the constructor argument on
Workerthat receives theIToolis called 'tool' (multipleParameterOverrideinstances can be passed toResolve). Any other dependencies (via constructor or property injection) that the named instance ofIWorkerhas should be correctly resolved as well.Alternatively, why not setup named
WorkerA, WorkerB, WorkerCinstances that require the specifiedITool...The disadvantage I suppose with the latter approach is that if
Workertakes additional constructor parameters you will need to specify them to theInjectionConstructoras well, specified in the same order as the constructor you are expecting Unity to use...However, Unity will lookup the non-named instance of
SomeDependencyandSomeOtherDependencyin the above example, so that saves you a bit of work.