Configuration Management
Relevant source files
The following files were used as context for generating this wiki page:Configuration management in this WEBAPI project is handled through a combination of .NET's built-in configuration system, environment variables, and Entity Framework Core's fluent API for database schema definition. This layered approach allows for flexible settings for different environments (e.g., Development, Production), dependency injection of services, and a code-first approach to database modeling.
The core of the configuration is managed at application startup in Program.cs, which reads settings from appsettings.json, registers services, and configures the HTTP request pipeline. Database entity configurations are modularized into separate classes, which are then applied by the UserDBContext to define the database schema.
Application Startup and Service Configuration
The Program.cs file is the entry point of the application and is responsible for setting up all services and middleware.
Sources: Program.cs
Service Registration
Services are registered with the dependency injection (DI) container using builder.Services. This allows for loose coupling and easy management of dependencies throughout the application.
The following diagram illustrates the flow of service and database context registration.
This diagram shows the sequence of configuration steps within Program.cs, from reading settings to registering the database context and application services.
Sources: Program.cs:11-40
Key services configured include:
| Service/Feature | Configuration Method | Description | Source File |
|---|---|---|---|
| Controllers | AddControllers() | Registers controllers and configures JSON serialization to ignore object cycles. | Program.cs:12-16 |
| API Explorer | AddEndpointsApiExplorer() | Used by Swagger/OpenAPI to discover API endpoints. | Program.cs:19 |
| Swagger | AddSwaggerGen() | Generates OpenAPI specification for the API. | Program.cs:20 |
| Database Context | AddDbContext<UserDBContext>() | Registers the EF Core DbContext with a SQL Server connection string from appsettings.json. | Program.cs:22-25 |
| Session State | AddDistributedMemoryCache() / AddSession() | Configures in-memory session storage with a 5-minute idle timeout. | Program.cs:28-34 |
| Application Services | AddTransient<IUserService, ...> / AddScoped<...> | Registers custom application services with specific lifetimes (Transient, Scoped). | Program.cs:36-38 |
HTTP Request Pipeline
The middleware pipeline is configured after the application is built. This defines how the application responds to HTTP requests.
- Development Environment: Swagger UI is enabled for API testing.
- CORS: A permissive Cross-Origin Resource Sharing (CORS) policy is configured to allow any origin, method, and header.
- Routing & Authorization: Standard authorization and controller endpoint mapping are enabled.
Sources: Program.cs:43-61
Application Settings
Configuration values are primarily stored in appsettings.json and can be overridden by environment-specific files like appsettings.Development.json.
Connection Strings
The database connection string is defined in appsettings.json.
{
"ConnectionStrings": {
"UserDataBase": "Server=MSI;Database=DongHo3;Trusted_Connection=true;TrustServerCertificate=True;"
}
}
Sources: appsettings.json:2-4
This connection string is retrieved in Program.cs to configure the UserDBContext.
// Program.cs
builder.Services.AddDbContext<UserDBContext>(option =>
{
option.UseSqlServer(builder.Configuration.GetConnectionString("UserDataBase"));
});
Sources: Program.cs:22-25
Launch Profiles
The Properties/launchSettings.json file defines profiles for running the application, including setting the ASPNETCORE_ENVIRONMENT variable to Development. This causes the application to load appsettings.Development.json and enable development-specific features like the Swagger UI.
| Profile | Command | Application URL | Environment |
|---|---|---|---|
http | Project | http://localhost:5048 | Development |
https | Project | https://localhost:7032;http://localhost:5048 | Development |
IIS Express | IISExpress | http://localhost:19162 | Development |
Sources: Properties/launchSettings.json
Entity Framework Core Configuration
The project uses a code-first approach with Entity Framework Core to define the database schema. Configuration is centralized in UserDBContext and modularized into individual IEntityTypeConfiguration<T> classes.
DbContext
UserDBContext serves as the main bridge between the application's entity models and the database. In its OnModelCreating method, it applies all the separate entity configuration classes.
// Data/UserDBContext.cs
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Apply all configurations
modelBuilder.ApplyConfiguration(new UserConfiguration());
modelBuilder.ApplyConfiguration(new OrderConfiguration());
modelBuilder.ApplyConfiguration(new ProductConfiguration());
modelBuilder.ApplyConfiguration(new AdminConfiguration());
modelBuilder.ApplyConfiguration(new CategoryConfiguration());
modelBuilder.ApplyConfiguration(new OrderItemConfiguration());
// ... additional relationship configurations
}
Sources: Data/UserDBContext.cs:13-28
Design-Time Factory
The UserDBContextFactory class allows EF Core tools (e.g., for creating migrations) to instantiate UserDBContext at design time. It explicitly reads the appsettings.json file to get the connection string, ensuring that tools can connect to the database without needing the application to be running.
This diagram shows how EF Core tools use the factory to get a configured DbContext instance.
Sources: Data/UserDBContextFactory.cs
Entity Type Configurations
Each database table is configured in its own class, promoting separation of concerns. These classes define table names, primary keys, column properties (like IsRequired, HasMaxLength), and relationships.
Example: Product Configuration
The ProductConfiguration class defines the schema for the Product table.
// Configuration/ProductConfiguration.cs
public class ProductConfiguration : IEntityTypeConfiguration<Product>
{
public void Configure(EntityTypeBuilder<Product> builder)
{
builder.ToTable("Product");
builder.HasKey(p => p.Id);
builder.Property(p => p.Title)
.IsRequired()
.HasMaxLength(100);
// ... other properties
builder.Property(p => p.Price)
.IsRequired()
.HasColumnType("decimal(18,2)");
}
}
Sources: Configuration/ProductConfiguration.cs:9-32
The following table summarizes constraints for the Product entity:
| Property | SQL Type | Required | Max Length |
|---|---|---|---|
Id | int | Yes (PK) | N/A |
Title | nvarchar | Yes | 100 |
Name | nvarchar | Yes | 200 |
Description | nvarchar | No | 500 |
Url | nvarchar | No | 200 |
Gender | nvarchar | No | 10 |
Price | decimal(18,2) | Yes | N/A |
ProductImageUrl | nvarchar | No | 500 |
Sources: Configuration/ProductConfiguration.cs:14-30, Migrations/UserDBContextModelSnapshot.cs:161-200
Database Schema
The combined configurations result in the following database schema. The diagram below represents the relationships between the main entities.
This ER diagram illustrates the database tables and their relationships as defined by the Entity Framework Core configurations.
Sources: Migrations/UserDBContextModelSnapshot.cs, Configuration/OrderConfiguration.cs:23-25, Configuration/OrderItemConfiguration.cs:20-26
Summary
The WEBAPI project employs a robust and conventional configuration strategy for a .NET application. It separates concerns effectively by using appsettings.json for environment-agnostic settings, Program.cs for service registration and pipeline setup, and dedicated Entity Framework Core configuration classes for defining the data model. This structure provides a clear, maintainable, and scalable foundation for the application's architecture.