简体   繁体   English

使用ninject绑定同一接口的不同实现

[英]Bind different implementations of same Interface using ninject

I use ninject to inject my dependencies in WPF project with MVVM approach. 我使用ninject通过MVVM方法在WPF项目中注入依赖项。 I have created UserControl that showing data in Grid, and contains a button. 我创建了UserControl ,它在Grid中显示数据,并包含一个按钮。 On button click every record in Grid is checked by my IChecker implementation injected by Ninject. 在按钮上单击时,Ninject注入的IChecker实现会检查Grid中的每个记录。 The problem is, I am using two instances of this UserControl with two instances of ViewModel bound into it's DataContext . 问题是,我正在使用此UserControl的两个实例,并将两个ViewModel实例绑定到其DataContext I want to pass diffrent implementations of my IChecker to diffrent instances of same type ViewModel . 我想将IChecker不同实现IChecker给相同类型ViewModel不同实例。 How can I achieve that with Ninject? 我如何用Ninject做到这一点?

You have multiple options, as specified in Ninject Contextual Binding documentation 如Ninject 上下文绑定文档中所指定,您有多个选项

Ninject WhenXXX WhenXXX

Some out of the box Contextual Bindings available are: 一些可用的现成上下文绑定是:

    Bind<IWarrior>().To<Ninja>();
    Bind<IWarrior>().To<Samurai>().WhenClassHas<ClimberNeeded>();
    Bind<IWarrior>().To<Samurai>().WhenTargetHas<ClimberNeeded>();
    Bind<IWarrior>().To<SpecialNinja>().WhenMemberHas<SwimmerNeeded>();
    Bind<IWarrior>().To<Samurai>().WhenInjectedInto(typeof(OnLandAttack));
    Bind<IWarrior>().To<SpecialNinja>().WhenInjectedInto(typeof(AmphibiousAttack));

Or you can provide a predicate and use custom logic wit hthe Target tinfo: 或者,您可以提供谓词并在目标信息中使用自定义逻辑:

Bind<IWarrior>().To<Samurai>().When(request => request.Target.Member.Name.StartsWith("Climbing"));
Bind<IWarrior>().To<Samurai>().When(request => request.Target.Type.Namespace.StartsWith("Samurais.Climbing"));

Custom Factory 定制工厂

If you're logic starts getting comlex for deciding when to inject what, you may want to implement a some sort of ICheckerFactory which will know which IChecker to create based on some parameters. 如果您的逻辑决定要何时注入什么内容变得复杂,您可能想要实现某种ICheckerFactory ,它将基于某些参数知道要创建哪个IChecker

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM