Global.asax is no more in ASP.NET Core application. Startup.cs file is a replacement of Global.asax file in ASP.NET Core. Startup class triggers at first when application launches.
The Startup class is a place where:
- Services are configured which are required by the application .
- The app's request handling pipeline is defined, as a series of middleware components.
Description.
Startup.cs is mandatory in the application, it can be decorated with any access modifier like public, private, internal. multiple Startup classes are allowed in a single application. ASP.NET Core will select the appropriate class based on its Enviroment.
If a class Startup{EnvironmentName} exists, that class will be called for that EnvironmentName.
Should we need to define class name with startup.cs? No it is not necessary that class name should be Startup.
We can define two method in startup file like ConfigureServices and Configure.
public class Startup
{
// Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
…
}
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
…
}
}
ConfigureServices Method :
This is an optional method in Startup class which is used to configure services for application. when any request come to application ConfigureService method will be called first.
ConfigureServices method includes IServiceCollection parameter to register services. This method must be declared with a public access modifier, so that environment will be able to read the content from metadata.
ASP.net core has built-in support for Dependency Injection. We can add services to DI container using this method. Following are ways to define ConfigureServices method in startup class.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
Configure Method :
The Configure method is used to specify how the application will respond in each HTTP request. this method is mostly used for registering middleware in HTTP pipeline. this method method accept IApplicationBuilder parameter along with some other services like IHostingEnvironment and ILoggerFactory. Once we add some service in ConfigureService method, it will be available to Configure method to be used.
public void Configure(IApplicationBuilder app)
{
app.UseMvc();
}
Above example shows to enable MVC feature in our framework we need to register UseMvc() into Configure and also need to register service AddMvc() into ConfigureServices.
Refrence: https://medium.com/
0 comments:
Post a Comment