Lesson 8 of 8
Mini Project: Typed Config Validation Service
Build a minimal ASP.NET Core API with strongly-typed configuration, startup validation, multiple service registrations by feature, health checks for DB+Redis, and a background worker - demonstrating all DI and hosting patterns from this module.
Quick Quiz - DI, Configuration & Hosting
Complete Project Wiring
// ━━ Full Program.cs with all patterns from this module ━━
var builder = WebApplication.CreateBuilder(args);
// ━━ Typed config with startup validation ━━
builder.Services.AddOptions<DatabaseOptions>()
.Bind(builder.Configuration.GetSection(DatabaseOptions.Section))
.ValidateDataAnnotations().ValidateOnStart();
builder.Services.AddOptions<JwtOptions>()
.Bind(builder.Configuration.GetSection(JwtOptions.Section))
.ValidateDataAnnotations().ValidateOnStart();
// ━━ Feature-based registration ━━
builder.Services
.AddApplication() // MediatR, AutoMapper, FluentValidation
.AddInfrastructure(builder.Configuration) // EF Core, Redis, repositories
.AddPresentation(); // Controllers, Swagger, Auth
// ━━ Background services ━━
builder.Services.AddSingleton<IEmailTaskQueue, EmailTaskQueue>();
builder.Services.AddHostedService<EmailBackgroundService>();
// ━━ Health checks ━━
builder.Services
.AddHealthChecks()
.AddSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")!, tags: ["ready"])
.AddRedis(builder.Configuration.GetConnectionString("Redis")!, tags: ["ready"]);
var app = builder.Build();
// ━━ Run startup DB migration (development only) ━━
if (app.Environment.IsDevelopment())
{
using var scope = app.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.MigrateAsync();
}
app.UseExceptionHandler("/error");
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapHealthChecks("/health/live", new() { Predicate = _ => false });
app.MapHealthChecks("/health/ready", new() { Predicate = c => c.Tags.Contains("ready") });
// ━━ Summary: config → register → build → middleware → run ━━
app.Run();
// Configuration validation ensures app fails fast if:
// - Connection string is missing
// - JWT secret key is too short (< 32 chars)
// - SMTP host is empty
// Rather than a cryptic NullReferenceException deep in HTTP handling at 3am
class AppDbContext : Microsoft.EntityFrameworkCore.DbContext { }
static class ServiceExtensions
{
public static IServiceCollection AddApplication(this IServiceCollection s) => s;
public static IServiceCollection AddInfrastructure(this IServiceCollection s, Microsoft.Extensions.Configuration.IConfiguration c) => s;
public static IServiceCollection AddPresentation(this IServiceCollection s) => s;
}
class DatabaseOptions { public const string Section = "Database"; [System.ComponentModel.DataAnnotations.Required] public string ConnectionString { get; init; } = ""; }
class JwtOptions { public const string Section = "Jwt"; [System.ComponentModel.DataAnnotations.Required][System.ComponentModel.DataAnnotations.MinLength(32)] public string SecretKey { get; init; } = ""; }Tip
Tip
Practice Mini Project Typed Config Validation Service in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of Mini Project Typed Config Validation Service from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Mini Project Typed Config Validation Service is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?