【问题标题】:What are the differences between ConfigureServices() and Configure() in ASP.NET Core?ASP.NET Core 中的 ConfigureServices() 和 Configure() 有什么区别?
【发布时间】:2018-07-19 11:45:29
【问题描述】:

docs.microsoft.com 上的文档说明如下:

使用 ConfigureServices 方法将服务添加到容器中。

使用 Configure 方法配置 HTTP 请求管道。

谁能用简单的例子解释一下,向容器添加服务是什么意思,配置HTTP请求管道是什么意思?

【问题讨论】:

标签: c# asp.net-core


【解决方案1】:

简而言之:

ConfigureServices用于配置依赖注入

public void ConfigureServices(IServiceCollection services)
{
    // register MVC services
    services.AddMvc();

    // register configuration
    services.Configure<AppConfiguration>(Configuration.GetSection("RestCalls")); 

    // register custom services
    services.AddScoped<IUserService, UserService>();
    ...
}

Configure用于设置中间件、路由规则等

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // configure middlewares
    app.UseMiddleware<RequestResponseLoggingMiddleware>();
    app.UseMiddleware<ExceptionHandleMiddleware>();

    app.UseStaticFiles();

    // setup routing
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "Default",
            template: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = 1 });

    });
}

阅读 ASP.NET Core fundamentals 以了解其工作原理的详细信息。

【讨论】:

【解决方案2】:

ConfigureServices 中的项目是 Dependency Injection 的一部分,例如记录器、数据库等。这些东西与 http 请求没有直接关联。

configure 中的项目是 http 请求 的一部分,例如路由、中间件、静态文件,所有这些都会在用户发出请求时直接触发。

【讨论】:

  • 我喜欢这个简短直接的回答。
猜你喜欢
  • 1970-01-01
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 2016-05-03
  • 1970-01-01
  • 2021-12-30
  • 2020-05-01
  • 2019-10-23
相关资源
最近更新 更多