Suppose I have an interface IA
, two implementations A1
and A2
and a dependent class B
that depends on IA
. Two implementations of the same interface in Windsor container are registered like this:
container.Register(Component.For<IA>()
.ImplementedBy<A1>());
container.Register(Component.For<IA>()
.ImplementedBy<A2>());
Is there are way to specify which implementation to use inside the dependent class B
?
For example in Autofac, I could use KeyFilterAttribute
like this:
class B
{
...
public B([KeyFilter("A1")]IA a)
{
...
}
}
There's a few ways to achieve this, and which one is most suitable depends on the bigger context.
If you register the components one by one, like in the sample code in question Windsor uses the first component registered as the default for the service. So inside your B
you're guaranteed to get the service implemented by A1
.
To be explicit you can force a component to be the default (works for registering by convention too
.
container.Register(
Component.For<IA>().ImplementedBy<A1>(),
Component.For<IA>().ImplementedBy<A2>().IsDefault());
B
to pick either A1
or A2
regardless of the defaults (which would be the closest to the Autofac.
container.Register(
Component.For<B>()
.DependsOn(Dependency.OnComponent<IA, A1>))