2012-10-28 73 views
0

我有一個ModuleLoader : NinjectModule這是我綁定一切的地方。Ninject窗體澄清

首先我用

Bind<Form>().To<Main>(); 

綁定一個System.Windows.Forms.FormMain形式。

這是正確的嗎?

其次在Program.cs中我用這個:

_mainKernel = new StandardKernel(new ModuleLoader()); 
var form = _mainKernel.Get<Main>(); 

_mainKernel是ninject標準的內核。

然後我用Application.Run(form)

這是正確的嗎?

對於Windows.Forms,我不確定要綁定在一起。

感謝您的任何幫助。

+1

您還沒有真正問了一個問題。確認[這裏](http://stackoverflow.com/questions/4129092/how-to-use-ninject-in-a-windows-forms-application)有什麼用處? –

回答

1

您不應該對System.Windows.Forms.Form有約束力。 Ninject主要用於綁定具體類型的接口,以便您可以將依賴關係作爲接口傳遞,並在運行時/測試期間切換具體實現。

如果您只是想使用Ninject以這種方式創建您的表單,您只需使用Bind<MyForm>().ToSelf(),然後再使用kernel.Get<MyForm>()。如果您直接請求具體類型並且不需要任何依賴關係,那麼使用Ninject來初始化它並沒有多大意義。

在你的情況下,如果你的表單實現了一個接口,那麼你會這樣做:Bind<IMainForm>().To<MainForm>()並從Ninject請求接口類型。通常你的界面不應該被綁定到「表單」的概念,它應該是不可知的實現(所以後面你可以生成一個CLI和網站版本,只需交換Ninject綁定)。

你可以使用模型 - 視圖 - 演示設計模式(或變體)來實現此類似:

public interface IUserView 
{ 
    string FirstName { get; } 
    string LastName { get; } 
} 

public class UserForm : IUserView, Form 
{ 
    //initialise all your Form controls here 

    public string FirstName 
    { 
     get { return this.txtFirstName.Text; } 
    } 

    public string LastName 
    { 
     get { return this.txtLastName.Text; } 
    } 
} 

public class UserController 
{ 
    private readonly IUserView view; 

    public UserController(IUserView view) 
    { 
     this.view = view; 
    } 

    public void DoSomething() 
    { 
     Console.WriteLine("{0} {1}", view.FirstName, view.LastName); 
    } 
} 

Bind<IUserView>().To<UserForm>(); 
Bind<UserController>().ToSelf(); 

//will inject a UserForm automatically, in the MVP pattern the view would inject itself though  
UserController uc = kernel.Get<UserController>(); 
uc.DoSomething();