2012-10-04 49 views
5

獲得實例下面是NinjectHttpApplication配置..如何從Ninject

public class MvcApplication : NinjectHttpApplication 
{ 
     public MvcApplication() 
     { 
      Error += NinjectWebsiteApplication_Error; 
     } 
}  

protected override IKernel CreateKernel() 
{ 
     var kernel = new StandardKernel(); 
     kernel.Load<ApplicationConfig>(); 
     return kernel; 
} 

void NinjectWebsiteApplication_Error(object sender, System.EventArgs e) 
{ 
     ILogger _iLogger = **//How to get instance of Applogger here from Ninject kernel..** 
} 

下面是ApplicationConfig類...

public class ApplicationConfig : NHibernateNinjectModule 
{ 

    public ApplicationConfig() 
    { 
    //other settings such as ddl script generation is present here 
    } 
    public override void Load() 
    {     
     base.Load(); 
     Bind<ILogger>().To<AppLogger>().InSingletonScope(); 
    } 
} 

回答

3
void NinjectWebsiteApplication_Error(object sender, System.EventArgs e) 
{ 
    var kernel = CreateKernel(); 
    ILogger _iLogger = kernel.Get<ILogger>(); 
} 

好,因爲它似乎NinjectHttpApplication商店生成內核對象在

public IKernel Kernel 
{ 
    get { return _kernel; } 
} 

所以你可以在上面重寫爲

void NinjectWebsiteApplication_Error(object sender, System.EventArgs e) 
{ 
    ILogger _iLogger = Kernel.Get<ILogger>(); 
} 
+0

感謝您的回覆。我們是否需要再次創建內核才能訪問實例?因爲在ApplicationConfig()中,我們有很多其他事情正在進行,例如爲應用程序創建ddl腳本。所以,當引發錯誤事件時,CreateKernel()被調用並且腳本再次生成。我意識到我也需要這個實例在動作過濾器中,並嘗試使用屬性上的「注入」屬性,但它給出的對象引用錯誤。在這種情況下是否注入屬性或只讀屬性的接口工作.. – Sunny

+0

我編輯了我的答案 – archil

+0

我們如何訪問_kernel變量。我需要這樣的東西?... http://stackoverflow.com/questions/5031678/getting-started-with-ninject-in-asp-net-mvc-3 – Sunny