2012-11-17 49 views
6

我迷失在Ninject在WPF中。WPF应用程序与Ninject

我在App.xaml中初始化它,但MainWindow.xaml中的ITest属性(即使使用InjectAttribute)没有得到解决,仍然为空。

public partial class App : Application 
{ 
    protected override void OnStartup(StartupEventArgs e) 
    {  
     IKernel kernel = new StandardKernel(); 
     kernel.Bind<ITest, Test>(); 
     base.OnStartup(e); 
    } 
} 

我google了一下,发现它不能这样工作。在试图找到解决方案时,我最终创建了IMainWindow,但没有其他任何内容,但“void Show();”并将其添加到MainWindow。

public partial class App : Application 
{ 
    protected override void OnStartup(StartupEventArgs e) 
    {  
     IKernel kernel = new StandardKernel(); 
     kernel.Bind<ITest, Test>(); 

     kernel.Bind<IMainWindow, MySolution.MainWindow>(); 
     kernel.Get<IMainWindow>().Show(); 

     base.OnStartup(e); 
    } 
} 

对于这一点,我得到一个NullReferenceException上的线与不用彷徨

我也试过这样:

public partial class App : Application 
{ 
    protected override void OnStartup(StartupEventArgs e) 
    {  
     IKernel kernel = new StandardKernel(); 
     kernel.Bind<ITest, Test>(); 

     MainWindow = new MySolution.MainWindow(kernel); 
     //then kernel.Inject(this); in the MainWindow constructor 
     MainWindow.Show(); 

     base.OnStartup(e); 
    } 
} 

现在我在.Inject线得到一个NullReferenceException在MainWindow中。

我发现了另一个不同的解决方案,但他们似乎重量级,我放弃了测试所有这些,并尝试哪一个工程。

请帮忙吗?

+0

究竟什么是你的'NullReferenceException'是什么? – AgentFire

回答

5

您没有正确注册您的类型,这就是为什么第二个示例会抛出一个错误。正确的语法是:kernel.Bind<SomeInterface>().To<SomeImplementation>()

所以,正确的用法:

protected override void OnStartup(StartupEventArgs e) 
{ 
    IKernel kernel = new StandardKernel(); 
    kernel.Bind<ITest>().To<Test>(); 

    kernel.Bind<IMainWindow>().To<MainWindow>(); 
    var mainWindow = kernel.Get<IMainWindow>(); 
    mainWindow.Show(); 

    base.OnStartup(e); 
} 

而且你需要与[Inject]属性来标记你的财产:

public partial class MainWindow : Window, IMainWindow 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
    } 

    [Inject] 
    public ITest Test { get; set; } 
} 

public interface IMainWindow 
{ 
    void Show(); 
} 
+0

呵呵,我以为绑定()就是绑定()。到()。显然不是。谢谢! – Mirek

+0

否与'绑定()'您可以将两个接口绑定到一个实现,但仍需要使用'.To <>'提供实现。 – nemesv

+0

我知道这是旧的,但当我这样做时,我得到两个主窗口显示,而不是一个。有什么想法吗? – JMK

0

我敢肯定,你得到了一个解决方案,但如果需要,您可以在MainWindow上使用构造函数注入而不是属性注入。

这可避免创建Dummy接口IMainWindow并为所有注入的类创建不必要的公共属性。

这里的解决方案:

MainWindow.cs

public partial class MainWindow : Window, IMainWindow 
{ 
    private readonly ITest test; 

    public MainWindow(ITest test) 
    { 
     this.test = test; 
     InitializeComponent(); 
    } 

} 

App.xaml.cs:

protected override void OnStartup(StartupEventArgs e) 
{ 
    IKernel kernel = new StandardKernel(); 
    kernel.Bind<ITest>().To<Test>(); 

    var mainWindow = kernel.Get<MainWindow>(); 
    mainWindow.Show(); 

    base.OnStartup(e); 
}