Role of Startup class in ASP.NET Core
ASP.NET Core apps use a Startup
class, which is named Startup by convention. However, we can give any name to the Startup class,
just specify it as the generic parameter in the UseStartup
ConfigureServices
method to configure the app's services. A service is a reusable component that provides app functionality.
Services are registered in ConfigureServices
and consumed across the app via dependency injection (DI)
or ApplicationServices.
ConfigureServices and Configure are called by the ASP.NET Core runtime when the app starts.
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } }
The Startup class must include a Configure method and can optionally include ConfigureService method.
ConfigureServices()
The ConfigureServices method is a place where you can register your dependent classes with the built-in IoC container. After registering dependent class, it can be used anywhere in the application. You just need to include it in the parameter of the constructor of a class where you want to use it. The IoC container will inject it automatically.
ASP.NET Core refers dependent class as a Service. So, whenever you read "Service" then
understand it as a class which is going to be used in some other class.
ConfigureServices method includes IServiceCollection parameter to register services to the IoC container.
Configure()
The Configure method is a place where you can configure application request pipeline for your application using IApplicationBuilder instance that is provided by the built-in IoC container.
ASP.NET Core introduced the middleware components to define a request pipeline, which will be executed on every request. You include only those middleware components which are required by your application and thus increase the performance of your application.
The following is default Configure() method:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Run(async (context) => { await context.Response.WriteAsync("DotNet Palace"); }); }