【问题标题】:What is the difference between services.Add and app.Use in startup class in ASP.NET Core?ASP.NET Core 启动类中的 services.Add 和 app.Use 有什么区别?
【发布时间】:2022-07-26 03:07:05
【问题描述】:

我开始学习 ASP.NET Core,在 Web API 模板的框架内,有一个 Startup 类,带有 ConfigureServices()Configure() 方法。

谁能告诉我如何使用它们?我正在观看 Udemy 课程,但我不明白讲师为什么这样做

public class Startup
{
    private readonly IConfiguration config;

    public Startup(IConfiguration config)
    {
        this.config = config;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationServices(this.config);
        services.AddControllers();
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebAPIv5", Version = "v1" });
        });
        services.AddCors();
        services.AddIdentityServices(this.config);

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        //if (env.IsDevelopment())
        //{
        //    app.UseDeveloperExceptionPage();
        //    app.UseSwagger();
        //    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAPIv5 v1"));
        //}
        app.UseMiddleware<ExceptionMiddleware>();

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors(x => x
                   .AllowAnyMethod()
                   .AllowAnyHeader()
                   .SetIsOriginAllowed(origin => true) // allow any origin
                   .AllowCredentials());

【问题讨论】:

  • 最短的答案是app.Use 向管道添加中间件,services.Add 在 IoC(服务)容器中注册服务。但是,您可能需要一些背景知识才能了解这一点,而最短的解释可能还不够。然后建议学习如何构建自定义中间件以及如何注册自定义服务(以及用于什么目的)。那么区别应该更清楚了。
  • 我会在课程中做到这一点,谢谢

标签: c# asp.net-core


【解决方案1】:

services.Add是注册服务,app.Use是使用Middleware的方式

Configure Service():用于向容器添加服务并配置这些服务。基本上,服务是一个用于应用程序中常见消费的组件。有MVC、EF核心、身份等框架服务。但也有特定于应用程序的应用程序服务,例如发送邮件服务。

Configure():用于指定 asp.net 核心应用程序将如何响应单个请求。通过这个,我们实际上构建了 HTTP 请求管道

public class Startup {
        
        // This method gets called by the runtime. 
          // Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services) {
            // Register services here through dependency injection
        }
  
        // This method gets called by the runtime. 
          // Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, 
                              IWebHostEnvironment env) {
            
            // Add middlware components here
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
            }
            app.UseRouting();
            app.UseEndpoints(endpoints => {
                endpoints.MapGet("/",async Context => {
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }
    }

阅读this example了解更多信息。

【讨论】:

    【解决方案2】:

    Configure.Services 和 Configure 是您可以在 ASP.NET Core 中配置框架级设置的起点。

    Configure.Services:添加所有服务,即您为向 API 添加业务、数据库逻辑而创建的类型。例如:您可能已经创建了自己的日志服务,并且需要通过 DI 注入其他类。要为这些 Logging 服务创建对象,您需要首先将其注册到 ASP.NET Core 的 IOC 容器中,并且 Configure.Services 是您添加这些服务的地方。

    配置:配置请求-响应管道,即处理传入请求和传出响应的类型。例如:您可能希望在请求到达您的控制器之前添加某种身份验证和授权。配置是您添加这些中间件的地方。

    【讨论】:

      猜你喜欢
      • 2020-05-01
      • 2015-01-25
      • 1970-01-01
      • 2015-02-14
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多