'How to inject a collection of a service into a strategy implementing that same service?
I have a service IService and an implementation StrategyService like that:
interface IService
{
// interface declaration here
}
class StrategyService: IService
{
IService[] services;
StrategyService(params IService[] services)
{
this.services = services;
}
// interface implementation here
}
Now let's say I have 2 implementations of IService: Service1 & Service2. I want to tell Castle Windsor to take instances of Service1 and Service2 as parameters for the component StrategyService.
Here is my test:
var container = new WindsorContainer();
container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));
container.Register(
Component.For<IService>().Instance(new Service1()).Named("service1"),
Component.For<IService>().Instance(new Service2()).Named("service2"),
Component.For<IService>().ImplementedBy<StrategyService>());
var service = container.Resolve<IService>();
// `service` is of type `Service1`
How can I get an instance of StrategyService with service1 and service2 as parameters?
Solution 1:[1]
Just invert the declaration of the components like this:
container.Register(
Component.For<IService>().ImplementedBy<StrategyService>(),
Component.For<IService>().Instance(new Service1()).Named("service1"),
Component.For<IService>().Instance(new Service2()).Named("service2"));
There is some magic here, has it seems to resolve the first component declared, but use only the two next ones excluding that first into the array to be injected.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hemel |
