如何在Windows Forms应用程序中使用Ninject?

19

我有一个WinForms应用程序,其中包含这个主窗体:

    ICountRepository countRepository;
    public MainForm(ICountRepository countRepository)
    {
        this.countRepository = countRepository;
    }

    public void IncrementCount()
    {
        countRepository.IncrementCount();
    }

但我在将ICountRepository注入到主窗体中遇到了困难。我该怎么做?


相关内容:https://dev59.com/hnnZa4cB1Zd3GeqPlQ46 - Ruben Bartelink
1个回答

23

首先需要进行的步骤是从以下内容切换:

var form = new MainForm();
Application.Run(form);

目标:

var kernel = new StandardKernel( new ModuleRegisteringICountRepository());
var form = kernel.Get<MainForm>();
Application.Run(form);

也许进行一两次澄清编辑,阐明您想要实现的目标类型,可以获得更详细的答案。
强烈推荐阅读@Mark Seemann的.NET中的依赖注入书籍,以了解与此相关的模式(按其说法,上述转换使Main成为组合根——Get 组成应用程序的对象图的(单个))。

1
我最终将此代码编写在Program.cs文件的主方法中。 - Attilah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接