简体   繁体   中英

What is the difference between services.Add and app.Use in startup class in ASP.NET Core?

I begin to learn ASP.NET Core, there, within the framework of the Web API template, there is a Startup class with ConfigureServices() and Configure() methods.

Can anyone tell me about how to use them? I am watching an Udemy course and I didn't understand why the instructor doing

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());

services.Add is to register service , app.Use is the way to use Middleware

Configure Service() : It is used to add services to the container and configure those services. basically, service is a component that is intended for common consumption in the application. There is framework service like MVC, EF core, identity so on. but there are also application services that are application-specific like send mail services.

Configure() : it is used to specify how the asp.net core application will respond to individual requests. Through this, we actually build the HTTP request pipeline

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!");
                });
            });
        }
    }

Read this example to know more.

Configure.Services and Configure are the starting points from where you can configure framework-level settings in ASP.NET Core.

Configure.Services: To add all the services ie the types that you created to add business, database logic to your API. eg: You might have created your own logging service and you need to inject in the other classes through DI. To create the objects for these Logging service you need to first register it in the IOC containter of the ASP.NET Core and Configure.Services is the place where you add those services.

Configure: To configure the request-response pipeline ie the types that handles the incoming request and outgoing response. eg: You might want to add some kind of authentication and authorization before request reaches your controller. Configure is the place where you add those middlewares.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM