在dotnetcore中获取DI容器

时间:2016-07-15 00:40:54

标签: c# asp.net-core-mvc

我想通过使用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 个答案:

答案 0 :(得分:1)

您是否尝试过app.ApplicationServices.GetRequiredService<LandingPageRouter>()

如果这不起作用,则表示控制器尚未注册服务。