2012-11-17 47 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); 
}