Roadmap › Modern .NET — Hosting, Configuration, DI & Deployment › Module: Hosting, Configuration, DI and Logging
Lessons in this course (9)
3. Generic host and Program.cs
Basic★ Must knowLesson 3 of 9
csharp
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Db")));
builder.Services.AddHostedService<OutboxPublisher>(); // background worker
var app = builder.Build();
if (app.Environment.IsDevelopment()) app.MapOpenApi();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();Non-web apps (worker services, console tools) use Host.CreateApplicationBuilder(args) and get the same configuration/DI/logging.
csharp
public class OutboxPublisher(ILogger<OutboxPublisher> log, IServiceScopeFactory scopes) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(10));
while (await timer.WaitForNextTickAsync(stoppingToken))
{
using var scope = scopes.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
// publish pending messages...
}
}
}