如何在ninject中将一个单例实例绑定到多个绑定方法

时间:2019-09-26 20:17:47

标签: c# dependency-injection inversion-of-control ninject

通过将MVVM框架与Ninject一起使用,我有不同的具体ViewModel类都绑定到IViewModel接口。我的问题是要在如何确定将哪个ViewModel注入到View中的灵活性。我希望能够使用Named(string)属性,ConstraintAttribute或基本Attribute来确定适当的ViewModel

换句话说,我希望所有这些返回一个单例的AlphaViewModel实例:

Bind<IViewModel>().To<AlphaViewModel>().WhenTargetHas<AlphaAttribute>();
Bind<IViewModel>().To<AlphaViewModel>().WhenMemberHas<AlphaAttribute>();
Bind<IViewModel>().To<AlphaViewModel>().WhenClassHas<AlphaAttribute>();

Bind<IViewModel>().To<AlphaViewModel>().Named("Alpha");

Bind<IViewModel>().To<AlphaViewModel>().WhenInjectedInto<AlphaView>();

我尝试过

A) Bind<IViewModel>().To<AlphaViewModel>().WhenInjectedInto<AlphaView>().InSingletonScope().Named("Alpha");
B) Bind<IViewModel>().To<AlphaViewModel>().WhenClassHas<AlphaAttribute>().InSingletonScope.Named("Alpha");

和类似的组合,但似乎使要求更加复杂。


A 仅在其设置如下时才具有正确的进样:

public partial class AlphaView : Window
{
    public AlphaView()
    {
        InitializeComponent();
    }
    public AlphaView([Named("Alpha")]IViewModel viewModel) : this()
    {
        DataContext = viewModel;
    }
}

B 有更多的回旋余地,因为View可以命名为其他名称,但是仍然需要两个参数才能注入ViewModel:

[AlphaAttribute]
public partial class BravoView : Window
{
    public BravoView()
    {
        InitializeComponent();
    }
    public BravoView([Named("Alpha")]IViewModel viewModel) : this()
    {
        DataContext = viewModel;
    }
}


当我想要的是能够使用任何一种“属性”或“名称”注入单例AlphaViewModel时,可以使用所有3个实例并指向同一个ViewModel。

[AlphaAttribute]
public partial class CharlieView : Window
{
    public CharlieView()
    {
        InitializeComponent();
    }
    public CharlieView(IViewModel viewModel) : this()
    {
        DataContext = viewModel;
    }
}

public partial class CharlieView : Window
{
    public CharlieView()
    {
        InitializeComponent();
    }
    public CharlieView([Named("Alpha")]IViewModel viewModel) : this()
    {
        DataContext = viewModel;
    }
}

public partial class CharlieView : Window
{
    public CharlieView()
    {
        InitializeComponent();
    }
    [AlphaAttribute]
    public IViewModel AlphaVM { get; set; }
}

1 个答案:

答案 0 :(得分:0)

这可以通过为AlphaViewModel设置单个单例绑定来实现

Bind<AlphaViewModel>().ToSelf().InSingletonScope();

n个绑定将请求“重定向”到AlphaViewModel,例如:

Bind<IViewModel>()
    .ToMethod(ctx => ctx.Kernel.Get<AlphaViewModel>())
    .WhenTargetHas<AlphaAttribute>();

...

Bind<IViewModel>()
    .ToMethod(ctx => ctx.Kernel.Get<AlphaViewModel>())
    .Named("Alpha");