Let's say I have a class that depends on interface IFace with several other dependencies injected into constructor (depicted by ...). I also have 2 implementations of the IFace interface.
class Impl1 : IFace {}
class Impl2 : IFace {}
class Std : IStd {
Std(IFace impl1, IOtherDependency otherDep, ...) { ... }
}
I want to register Impl1 as the default implementation and register Impl2 as named implementation which should be injected into certain classes.
container.RegisterType<IFace, Impl1>();
container.RegisterType<IFace, Impl2>("impl2");
Registering Std like this would inject the default Impl1 implementation:
container.RegisterType<IStd, Std>(); // this would inject the default implementation Impl1
How can I register Std to have the named implementation injected without resorting to calling Resolve() manually? The best I could come up with is this:
container.RegisterType<IStd, Std>(
new InjectionConstructor(new ResolvedParameter<IFace>("impl2"), typeof(IOtherDependency, ...)));
What I don't like with the above way is that I still need to specify all other constructor parameters; when the signature changes, I need to adjust the registration, the compiler doesn't pick up the problem (runtime exception is thrown) and intellisense doesn't work here.
What I would like to have is something along the lines of: (the InjectNamedType is obviously made up)
container.RegisterType<IStd, Std>(
InjectNamedType<IFace>(name: "impl2")); // this would tell Unity to look for registration of IFace with that name
Here is how you can do it:
container.RegisterType<IStd>(
new InjectionFactory(x =>
x.Resolve<Std>(new DependencyOverride<IFace>(x.Resolve<IFace>("impl2")))));
InjectionFactory allows you to specify the factory logic that creates the IStd object. We use the Resolve method to resolve the concrete Std class and we use the DependencyOverride class to specify which implementation of IFace to use. Again we use the Resolve method to resolve a specific implementation.
Please note that the factory logic will only run when someone tries to resolve IStd (or a class that depends on IStd), not when you register IStd.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With