This is my first post here, hoping to start also posting more often in the future :)
I have been trying to learn to use Castle Windsor rather than using Ninject but there's one feature I haven't been able to sort of "translate" to use in Windsor, and that is WhenInjectedInto.
Here's one example taken from Pro ASP.NET MVC 5 book, with Ninject
kernel.Bind<IValueCalculator>().To<LinqValueCalculator>();
kernel.Bind<IDiscountHelper>().To<FlexibleDiscountHelper>().WhenInjectedInto<LinqValueCalculator>();
This is a conditional binding, meaing that when it's LinqValueCalculator that is being bound to IValueCalculator, it should use FlexibleDiscountHelper when binding to IDiscountHelper, rather than any other object.
How can I replicate this with Windsor, if it's even possible ?
So far I have:
container.Register(Component.For<IValueCalculator>().ImplementedBy<LinqValueCalculator>());
container.Register(Component.For<IDiscountHelper>().ImplementedBy<FlexibleDiscountHelper>());
Thanks in advance, Bruno
I would just use DependsOn
:
container.Register(
Component.For<IDiscountHelper>()
.ImplementedBy<FlexibleDiscountHelper>());
container.Register(
Component.For<IValueCalculator>()
.ImplementedBy<LinqValueCalculator>()
.DependsOn(Dependency.OnComponent<IDiscountHelper, FlexibleDiscountHelper>());
There are a number of different ways to specify this dependency, check out the documentation if this specification isn't exactly what you need.
Yes, it's possible.
The nearest equivalent to Ninject's When
would probably be the IHandlerSelector
interface, which allows you to select a given handler based on some predicate, which in the case of the IHandlerSelector
is the return value of the HasOpinionAbout
method.
Ayende has an example for how HandlerSelectors can be used on his blog.
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