2010-07-30 71 views
2

我一直在尋找一段時間。C#ASP.NET(不是MVC)的Ninject 2.0的依賴注入

我不是新來的依賴注入,並使用StructureMap與幾個項目MVC之類的,但我覺得給Ninject一個去,以免錯過的樂趣。

我正在嘗試將Ninject與現有的網絡應用程序一起使用,該應用程序正在進行更新。

我無法找到Ninject提供的博客和wiki,我有點不耐煩,說實話,可能錯過了它,谷歌的前幾頁似乎過時或談論使用MVC與Ninject。

到目前爲止,我有以下幾點,它的工作原理,但我希望有人可以指出一個不太乾擾的選項,關於將ServiceModule調用到內核並從Web應用程序注入具有所需綁定的屬性。

我至今是一個ServiceModule:

public class ServiceModule : NinjectModule 
{ 
    public override void Load() 
    { 
     string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; 
     Bind<IPreRegistrationService>().To<PreRegistrationService>() 
      .WithConstructorArgument("connectionString",connectionString); 
    } 
} 

然後在我的網頁我已經定義了一個私有變量:在頁面加載事件

private IPreRegistrationService xfemPreRegistrationService = null; 

然後:

IKernel kernel = new StandardKernel(new ServiceModule()); 
    xfemPreRegistrationService = kernel.Get<IPreRegistrationService>(); 

所以這個工作,但我想要移動到一個階段,我所定義的是:

[Inject] 
public IPreRegistrationService xfemPreRegistrationService { get; set; } 

在頁面上,其餘的是魔術。

乾杯

回答

2

感謝this stackoverflow post我發現了關於延長Ninject.Web

的問題,我發現,你需要開始使用Ninject.Web,我不能,因爲我已經定義來處理證券PageBase和這樣的。

所以,我能看到的唯一途徑是採取從項目中KernelContainer class(如KernelContainer被定義爲內部):

然後從全球ASAX OnApplicationStart撥打:

KernelContainer.Kernel = new StandardKernel(new ServiceModule()); 

// Request injections for the application itself. 
KernelContainer.Inject(this); 

然後在我PageBase從OnInit方法:

KernelContainer.Inject(this); 

這已經讓我達到乾脆把我的目標:

[Inject] 
public IPreRegistrationService xfemPreRegistrationService { get; set; } 

需要的地方