Startup of ASP.NET Core Web App
Startup of a Web Application
The startup process of an ASP.NET Core web application is a crucial phase where the application is initialized, configured, and prepared to handle incoming HTTP requests.
Initialize, configure and execute
The Program class contains the Main method and this is the starting point of the application. The Startup process can be summarized into three steps:
Creating the Builder
In this step, you create a WebApplication instance and register services and dependencies using the builder.Services property. This step focuses on preparing the application for configuration.
var builder = WebApplication.CreateBuilder(args) // Add services to the container. builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddDbContext<SomeDBContext>();
Building the App
After registering services, you call builder.Build() to build the application, which includes setting up the dependency injection container with the registered services. This step is about preparing the application for execution.
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
Running the App
Once the application is built, you call app.Run() to start the application, making it listen for incoming HTTP requests and handle them according to the configured middleware and services.
app.Run();
Why use a separate Startup Class
The use of a separate Startup class is a best practice for maintaining clean and organized code.
- It follows the principle of separation of concerns, as configuration and service registration are isolated from the Main method.
- The Startup class is reusable, making it easier to configure the application differently for various environments.
- Code organization, testability, and readability are all improved by separating configuration from the Main method.
Example
Program class
The Program's Main() method calls the CreateHostBuilder method to create a host and then calls Build() to build the host, and finally, Run() to start the application:
namespace WebApp;
public class Program {
public static void Main(string[] args) {
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(
webBuilder => { webBuilder.UseStartup<Startup>(); }
)
;
}
This sets up default configurations and specifies that the application is a web application using ConfigureWebHostDefaults. The UseStartup<Startup>() method specifies that the Startup class will be used to configure the web host.
Startup class
public class Startup {
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
// This method is used to configure services.
public void ConfigureServices(IServiceCollection services) {....}
// This method is used to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {....}
}
- The constructor of the
Startupclass takes anIConfigurationparameter, which is used to access configuration settings for the application. - As the application starts, the framework automatically calls the
ConfigureServicesmethod within theStartupclass to configure and register the services and dependencies you have defined, like database context, repositories, query handlers, mapper, controllers, Swagger, etc.. - After
ConfigureServicescompletes, the framework will call theConfiguremethod in theStartupclass to configure the HTTP request pipeline: HTTPS redirection, routing and endpoint mapping for API controllers.
Configuration Loading
When your ASP .NET Core application starts, it automatically loads configuration settings from various sources, including appsettings.json, environment variables, command-line arguments and more.
{
"ConnectionStrings": {
"DefaultConnection": "Server=myServer;Database=myDatabase;User=myUser;Password=myPassword;"
},
"AppSettings": {
"Setting1": "Value1",
"Setting2": "Value2"
}
}
The Configuration property in the Startup class represents the application's configuration settings in a structured way. It is of type IConfiguration and is provided by the ASP.NET Core framework. You can access configuration settings from the Configuration object using indexing or extension methods:
string connectionString = Configuration.GetConnectionString("DefaultConnection");
string settingValue = Configuration["AppSettings:Setting1"];
Configuration Overrides
Configuration settings can be overridden or extended in different environments or through environment variables. For example, you can have separate appsettings.Development.json and appsettings.Production.json files for environment-specific configurations. The settings in these files will override the base appsettings.json when running in the corresponding environment.