Ninject功能(WhenInjectedInto)相当于Windsor

Bru*_*ues 5 .net c# dependency-injection castle-windsor asp.net-mvc-5

这是我在这里发表的第一篇文章,希望将来也能更频繁地发帖:)

我一直在努力学习使用Castle Windsor而不是使用Ninject,但有一个功能我无法在Windsor中使用"translate",那就是WhenInjectedInto.

以下是使用Ninject从Pro ASP.NET MVC 5书中获取的一个示例

kernel.Bind<IValueCalculator>().To<LinqValueCalculator>();
kernel.Bind<IDiscountHelper>().To<FlexibleDiscountHelper>().WhenInjectedInto<LinqValueCalculator>();
Run Code Online (Sandbox Code Playgroud)

这是一个条件绑定,意味着当它绑定到IValueCalculator的LinqValueCalculator时,它应该在绑定到IDiscountHelper时使用FlexibleDiscountHelper,而不是任何其他对象.

如果有可能的话,我怎么能和温莎一起复制呢?

到目前为止,我有:

container.Register(Component.For<IValueCalculator>().ImplementedBy<LinqValueCalculator>());
container.Register(Component.For<IDiscountHelper>().ImplementedBy<FlexibleDiscountHelper>());
Run Code Online (Sandbox Code Playgroud)

先谢谢,布鲁诺

Pat*_*irk 4

我只想使用DependsOn

container.Register(
    Component.For<IDiscountHelper>()
             .ImplementedBy<FlexibleDiscountHelper>());

container.Register(
    Component.For<IValueCalculator>()
             .ImplementedBy<LinqValueCalculator>()
             .DependsOn(Dependency.OnComponent<IDiscountHelper, FlexibleDiscountHelper>());
Run Code Online (Sandbox Code Playgroud)

有多种不同的方法可以指定此依赖项,如果此规范不完全符合您的需要,请查看文档。