Skip to content

4.3 — Program.cs: Generic Host vs Minimal Hosting

← Roadmap · Section: 4. Fundamentals and Application Startup Prev: 4.2 Hosting model · Next: 4.4 The legacy Startup.cs model

Markers: 🔥 💻 · Confidence: 🔴 · Last reviewed: —


TL;DR

Program.cs is where your application is assembled. It has exactly two phases, split by one line: builder.Build().

  • Before Build() you register services — what exists. After it you build the pipeline — what happens to a request.
  • Minimal hosting (WebApplication.CreateBuilder) is the modern default, since .NET 6. Everything in one file.
  • You cannot add services after Build(). That is the single most common error here.

Definitions

Term What it is What it means
Program.cs a file The entry point. Assembles and starts the application.
Host an object Owns dependency injection, configuration, logging and the server. Manages startup and shutdown.
Generic Host the older model Host.CreateDefaultBuilder() plus a separate Startup class. Still supported.
Minimal hosting the current model WebApplication.CreateBuilder(). One file, no Startup class. Default since .NET 6.
WebApplicationBuilder a class What CreateBuilder returns. Holds Services, Configuration, Environment, Logging.
WebApplication a class What Build() returns. The running app. You call Use..., Map... and Run() on it.
builder.Services a property The IServiceCollection. Where you register services. See 6.2.
builder.Configuration a property The IConfiguration. Reads appsettings.json, environment variables and more.
builder.Build() a method Creates the app and freezes the service collection. The dividing line.
app.Run() a method Starts the server and blocks until shutdown. Always last.
Top-level statements a C# feature Writing code without a Main method or class. Why Program.cs has no boilerplate.
WebApplicationFactory a test class Boots your whole app in memory for integration tests. Needs Program to be reachable.

The concept

The two phases

Every Program.cs has the same shape, and understanding it is most of this topic:

var builder = WebApplication.CreateBuilder(args);

// ═══ PHASE 1: REGISTER ═══
// "What services can be injected? What is available?"
builder.Services.AddControllers();
builder.Services.AddScoped<IOrderService, OrderService>();

var app = builder.Build();          // ◄── the dividing line

// ═══ PHASE 2: CONFIGURE ═══
// "What happens to an incoming request, and in what order?"
app.UseAuthentication();
app.MapControllers();

app.Run();                          // start listening, block until shutdown

A picture: phase 1 is stocking the kitchen; phase 2 is writing the recipe.

You cannot cook with an ingredient you did not buy, and you cannot buy ingredients once you have started cooking. builder.Build() is the moment the shop closes.

That is why builder.Services.Add... after Build() throws. The service collection is frozen so the container can be constructed. The error message — "Services cannot be added after the application is built" — is clear once you know the model and baffling before.

Why it looks so short

Two C# features remove the boilerplate:

Top-level statements (C# 9) let you write code with no Main method and no class. The compiler generates them.

Implicit usings (3.7) add the common namespaces automatically, so there is no using block.

What you write:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello");
app.Run();

What the compiler effectively produces:

internal class Program
{
    private static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        // ...
    }
}

That generated Program class is internal, which matters for testing — see the trap later.


How it works

The simple version — what CreateBuilder sets up for you

That one line does a surprising amount:

var builder = WebApplication.CreateBuilder(args);

It configures:

  • Configuration sources, in order of increasing priority: appsettings.json, then appsettings.{Environment}.json, then User Secrets in development, then environment variables, then command-line arguments. See 7.1.
  • Logging — console and debug providers.
  • Dependency injection — the built-in container.
  • Kestrel as the web server, plus IIS integration if present.
  • The content root — the folder the app treats as its base.

You get a working, configurable, logging application from one line, and can override any part of it.

The three objects you use

var builder = WebApplication.CreateBuilder(args);

builder.Services;          // register services (IServiceCollection)
builder.Configuration;     // read settings (IConfiguration)
builder.Environment;       // which environment am I in? (IWebHostEnvironment)
builder.Logging;           // configure logging providers
builder.Host;              // deeper host configuration
builder.WebHost;           // deeper server configuration (Kestrel, URLs)

var app = builder.Build();

app.Services;              // the BUILT container — resolve services from here
app.Configuration;         // same configuration
app.Environment;           // same environment

Note builder.Services (register into) versus app.Services (resolve from). Both exist and they are different things.

How it actually works — Generic Host vs Minimal Hosting

Before .NET 6, Program.cs and Startup.cs were two separate files:

// Program.cs — the OLD Generic Host model
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>();
            });
}
// Startup.cs — the two phases, as two methods
public class Startup
{
    public void ConfigureServices(IServiceCollection services)   // phase 1
    {
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)   // phase 2
    {
        app.UseRouting();
        app.UseEndpoints(e => e.MapControllers());
    }
}

The two phases were always there — they were just two methods in a separate class. Minimal hosting flattened them into one file.

Generic Host + Startup Minimal hosting
Files Program.cs + Startup.cs Program.cs only
Phase 1 ConfigureServices Before builder.Build()
Phase 2 Configure After builder.Build()
Since .NET Core 3.0 .NET 6
Status Still supported The default

Both still work. A .NET 8 app can use the Startup pattern, and plenty of older codebases do. You should recognise both — see 4.4.

The deeper detail — keeping it organised as it grows

Program.cs becomes unreadable at around forty registrations. The standard fix is extension methods on IServiceCollection (1.14):

// In Orders/OrderModuleExtensions.cs — next to the code it registers
public static class OrderModuleExtensions
{
    public static IServiceCollection AddOrderModule(
        this IServiceCollection services,
        IConfiguration config)
    {
        services.AddScoped<IOrderRepository, EfOrderRepository>();
        services.AddScoped<IOrderService, OrderService>();
        services.Configure<OrderOptions>(config.GetSection("Orders"));
        return services;                 // return it so calls can chain
    }
}
// Program.cs stays readable
builder.Services
    .AddOrderModule(builder.Configuration)
    .AddPaymentModule(builder.Configuration)
    .AddNotificationModule(builder.Configuration);

Two benefits beyond tidiness: each module's registrations live next to that module's code, so deleting a feature does not leave orphaned lines in Program.cs, and it is how every built-in Add... method works, so it reads as idiomatic.

⚠️ Making Program visible to tests

Integration tests use WebApplicationFactory<Program> to boot the real app in memory (20.7). But the compiler-generated Program class is internal, so the test project cannot see it.

Two fixes. In the web project's .csproj:

<ItemGroup>
  <InternalsVisibleTo Include="MyApp.Tests" />
</ItemGroup>

Or at the bottom of Program.cs:

public partial class Program { }     // makes the generated class public

That one-line class at the end of Program.cs looks bizarre if you do not know why it is there. It exists purely so tests can reference the type.


Code

A realistic production Program.cs:

var builder = WebApplication.CreateBuilder(args);

// ══════════ PHASE 1: services ══════════

builder.Services.AddControllers();
builder.Services.AddOpenApi();

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
        builder.Configuration.GetSection("Jwt").Bind(options));
builder.Services.AddAuthorization();

builder.Services.AddHealthChecks()
    .AddDbContextCheck<AppDbContext>();

// Feature modules, each registering its own dependencies
builder.Services
    .AddOrderModule(builder.Configuration)
    .AddPaymentModule(builder.Configuration);

var app = builder.Build();

// ══════════ PHASE 2: pipeline ══════════
// ORDER MATTERS HERE — see 5.2

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();                     // never expose the schema in production
}
else
{
    app.UseExceptionHandler("/error");    // friendly errors, no stack traces
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseAuthentication();                  // who are you?
app.UseAuthorization();                   // are you allowed?

app.MapControllers();
app.MapHealthChecks("/healthz");

app.Run();

Read it top to bottom and you can see the entire application: what it depends on, how it authenticates, what it exposes, and how it behaves differently in development. That readability is the point of the design.

Running code once at startup

A common need — apply database migrations, seed data, warm a cache. Do it between Build() and Run(), and create a scope:

var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
    var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
    await db.Database.MigrateAsync();
}

app.Run();

⚠️ The CreateScope() is not optional. AppDbContext is registered as scoped, and there is no ambient scope at startup — resolving it directly from app.Services throws. See 6.5.

⚠️ And auto-migrating on startup is contentious. With several instances starting at once, they all try to migrate simultaneously. It is convenient in development and a real risk in production, where migrations usually belong in the deployment pipeline — 14.9.


Interview questions

Q: Walk me through what Program.cs does.

It assembles and starts the application, in two phases separated by builder.Build(). Before that line you register services into the dependency injection container — what the application has available. After it you build the middleware pipeline — what happens to an incoming request and in what order. Then app.Run() starts the server and blocks until shutdown. The one-line WebApplication.CreateBuilder(args) at the top sets up configuration sources, logging, the DI container and Kestrel with sensible defaults, which is why the file can be so short.

Q: What is the difference between the Generic Host model and minimal hosting?

They are the same two phases arranged differently. The Generic Host model had Program.cs build a host that pointed at a separate Startup class, where ConfigureServices was phase one and Configure was phase two. Minimal hosting, the default since .NET 6, flattens that into a single Program.cs using top-level statements — registration before Build(), pipeline after. Both still work, and plenty of existing codebases use Startup, so it is worth recognising either.

Q: Why can't you register services after builder.Build()?

Because Build() constructs the dependency injection container from the service collection, and at that point the collection is frozen — the container needs a fixed set of registrations to resolve against. Adding afterwards throws with a message about services not being addable after the application is built. It is a common mistake when someone moves a registration line while reorganising the file.

Q: How would you run a one-off task at startup, like applying migrations?

Between builder.Build() and app.Run(), creating a scope first with app.Services.CreateScope(). The scope matters because things like DbContext are registered scoped and there is no ambient request scope during startup, so resolving directly from app.Services throws. I would also be careful about auto-migrating in production — with several instances starting simultaneously they all attempt it at once, so migrations usually belong in the deployment pipeline rather than in application startup.


Traps ⚠️

  • Adding services after builder.Build() throws. The collection is frozen.
  • Resolving a scoped service directly from app.Services throws. Create a scope first.
  • Middleware order is not the same as registration order. Service registration order does not matter; pipeline order matters enormously — see 5.2.
  • app.Run() blocks. Anything written after it never executes.
  • WebApplicationFactory<Program> fails to compile because the generated Program is internal. Add public partial class Program { } or InternalsVisibleTo.
  • Auto-migrating on startup races when several instances start together.
  • app.Run(...) with a delegate is different from app.Run(). The overload with a parameter is terminal middleware, not "start the app" — 5.3.


Sources