Injecting concrete implementations using Unity
I have 2 interface implementations where I need to inject the first implementation into one service and the second into another. Each service is also injected with other dependencies that do not have multiple implementations.
So far I have had something like this:
public FirstService(IDataRepository dr, IOtherRepository or)
{
this.DataRepository = dr;
this.OtherRepository = or;
}
public SecondService(IDataRepository dr, IAnotherRepository ar)
{
this.DataRepository = dr;
this.OtherRepository = ar;
}
Then in my bootloader, I:
container.RegisterType<IDataRepository, FirstDataRepository>("First");
container.RegisterType<IDataRepository, SecondDataRepository>("Second");
container.RegisterType<IOtherRepository ,OtherRepositor>();
container.RegisterType<IAnotherRepository ,AnotherRepository>();
container.RegisterType<IFirstService, FirstService>(new InjectionConstructor(new ResolvedParameter<IDataRepository>("First")));
container.RegisterType<ISecondService, SecondService>(new InjectionConstructor(new ResolvedParameter<IDataRepository>("Second")));
When I run my application, I get the error "FirstService does not have a constructor that takes parameters (IDataRepository)".
Do I also need to specify the IOtherRepository instance to be injected currently when I specifically specify the IDataRepository instance to be injected? Or am I doing something else wrong?
My actual constructor takes 6 arguments and it would be painful to manually enter each one just because one of them has multiple implementations.
source to share
You don't need to supply values ββfor the other parameters, but you do need to supply them Type
so that Unity can figure out which constructor to use.
Registration for IFirstService
will look like this:
container.RegisterType<IFirstService, FirstService>(new InjectionConstructor(new ResolvedParameter<IDataRepository>("First"), typeof(IOtherRepository)));
The codeplex TecX project includes ClozeInjectionConstructor
one that deals with situations where you only want to specify one parameter. See the source code in the TecX.Unity project.
Btw: 6 parameters for the constructor is the code smell for the constructor for the anti-pattern injection .
source to share
container.RegisterType<IFirstService, FirstService>(new InjectionConstructor(new ResolvedParameter<IDataRepository>("First"), new ResolvedParameter<IOtherRepository>()));
container.RegisterType<ISecondService, SecondService>(new InjectionConstructor(new ResolvedParameter<IDataRepository>("Second"), new ResolvedParameter<IAnotherRepository>()));
You need to solve the second constructor.
source to share