What are the differences between ConfigureServices() and Configure() in ASP.NET Core?

C#asp.net Core

C# Problem Overview


The documentation on docs.microsoft.com states the following:

> Use ConfigureServices method to add services to the container. > > Use Configure method to configure the HTTP request pipeline.

Can someone explain with simple examples, what is meant by adding services to container and what is meant by configuring HTTP request pipeline?

C# Solutions


Solution 1 - C#

In a nutshell:

ConfigureServices is used to configure Dependency Injection

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 is used to set up middlewares, routing rules, etc

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

Read ASP.NET Core fundamentals to understand how it works in details.

Solution 2 - C#

Items in ConfigureServices are part of Dependency Injection like logger, Database etc. These kind of things aren't directly associated with a http request.

Items in configure are part of a http request like routing, mididlewares, static files all these triggers directly when user makes a request.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFarooq HanifView Question on Stackoverflow
Solution 1 - C#Alex RiabovView Answer on Stackoverflow
Solution 2 - C#Krishnadas PCView Answer on Stackoverflow