2011-04-08 80 views
0

我在我的Global.ascx.cs文件中使用來自OnApplicationStarted的服務。有沒有辦法從那裏依賴注入存儲庫?Ninject從OnApplicationStarted注入​​依賴項

我的代碼:

public class MvcApplication : NinjectHttpApplication 
{ 
    //Need to dependency inject this. 
    private IBootStrapService bootService; 

    protected override void OnApplicationStarted() 
    { 
     //Used to set data such as user roles in database on a new app start. 
     bootService.InitDatabase(); 

     base.OnApplicationStarted(); 

     AreaRegistration.RegisterAllAreas(); 
     RegisterGlobalFilters(GlobalFilters.Filters); 
     RegisterRoutes(RouteTable.Routes); 
    } 

    internal class SiteModule : NinjectModule 
    { 
     public override void Load() 
     { 
      //I set my bindings here. 
      Bind<IBootStrapService>().To<BootStrapService>(); 
      Bind<IUserRepository>().To<SqlServerUserRepository>() 
       .WithConstructorArgument("connectionStringName", "MyDb"); 
     } 
    } 
} 

所以我怎麼ninject做DI權的內部應用程序啓動?正如你所看到的,我在SiteModule類中設置了我的綁定。

回答

1

您可以覆蓋CreateKernel方法,你會註冊模塊:

protected override IKernel CreateKernel() 
{ 
    return new StandardKernel(
     new INinjectModule[] 
     { 
      new SiteModule() 
     } 
    ); 
} 

這不會自動儘管注入bootService領域。你可以像這樣實例化:

protected override void OnApplicationStarted() 
{ 
    base.OnApplicationStarted(); 

    //Used to set data such as user roles in database on a new app start. 
    var bootService = Kernel.Get<IBootStrapService>(); 
    bootService.InitDatabase(); 

    AreaRegistration.RegisterAllAreas(); 
    RegisterGlobalFilters(GlobalFilters.Filters); 
    RegisterRoutes(RouteTable.Routes); 
} 
+0

因此,在完成此操作之後,服務將在OnApplicationStarted中的代碼執行之前注入? – 2011-04-08 06:20:42

+0

@Lol編碼器,不,在這種情況下'bootService'不會自動注入,因爲它是Http應用程序的一部分,Ninject不能控制它的實例化。你可以手動注入它。我會更新我的帖子以展示一個例子。 – 2011-04-08 06:24:25