Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 624
Farooq Hanif Avatar asked Jul 19 '18 11:07

Farooq Hanif


1 Answers

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.

like image 164
Alex Riabov Avatar answered Sep 18 '22 10:09

Alex Riabov