Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ninject feature (WhenInjectedInto) equivalent in Windsor

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

like image 376
Bruno Marques Avatar asked Nov 10 '14 23:11

Bruno Marques


2 Answers

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.

like image 111
Patrick Quirk Avatar answered Oct 11 '22 16:10

Patrick Quirk


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.

like image 31
Russ Cam Avatar answered Oct 11 '22 17:10

Russ Cam