2016-07-15 98 views
0

我想通過使用DI容器在應用程序的啓動配置中獲取路由的實例,而不是硬編碼實例,有沒有辦法做到這一點?在dotnetcore中獲取DI容器

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory){ 
    loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
    loggerFactory.AddDebug(); 
    if (env.IsDevelopment()) 
    { 
     app.UseDeveloperExceptionPage(); 
     app.UseBrowserLink(); 
    } 
    else 
    { 
     app.UseExceptionHandler("/Home/Error"); 
    } 
    app.UseStaticFiles(); 
    app.UseMvc(routes => 
    { 
     routes.MapRoute(
      "default", 
      "{controller=Home}/{action=Index}/{id?}"); 
     // hardcoded dependeny, I'd like to do something like this 
     // var instance = container.getInstance<LandingPageRouter>(); 
     routes.Routes.Add(new LandingPageRouter(routes, new MyWebRequest())); 
    }); 
} 

回答

1

您試過app.ApplicationServices.GetRequiredService<LandingPageRouter>()

如果這不起作用,則表示控制器尚未註冊服務。

+0

感謝您的幫助,但我收到了這個異常:「沒有爲'Main.Config.LandingPageRouter'類型的服務註冊。」 –

+0

我不確定我的理解。如果它不在DI容器中,則意味着它沒有註冊爲服務。您可以在啓動類的'ConfigureServices'方法之前嘗試執行'services.AddScoped ();'。 –

+0

其實,我忘了在註冊時添加它,所以我用addTransient註冊它,你能解釋AddScoped之間的區別嗎? –