loading experience

Guide

Guide to running .NET in production: publishing, observability and configuration

Guide to running .NET in production: publishing, observability and configuration

Publishing ASP.NET Core on IIS in self-contained mode, building containers without a Dockerfile, observability with OpenTelemetry and health checks, Aspire, resilient HttpClient, structured logging, the Options pattern and Dependency Injection: everything needed to take a .NET application to production.

In this guide

  1. Publishing ASP.NET Core on IIS: self-contained, in-process and diagnostics
  2. Containers for .NET apps without a Dockerfile
  3. Observability in .NET: OpenTelemetry and health checks
  4. Aspire: orchestrating distributed applications in development
  5. Resilient HttpClient in .NET: retry, timeout and circuit breaker
  6. Structured logging in .NET with LoggerMessage
  7. Configuration in .NET: the Options pattern and validation at startup
  8. Dependency Injection in .NET: lifetimes and keyed services

Publishing ASP.NET Core on IIS: self-contained, in-process and diagnostics

Many Windows hosting providers run ASP.NET Core applications on IIS. Publishing is simple, but when the app does not start the errors say little. Here is what we learned in production.

Checking the files before reactivating the site avoids failed startups.
Checking the files before reactivating the site avoids failed startups.

Framework-dependent or self-contained?

  • Framework-dependent: small package, but the right runtime (Hosting Bundle) must be installed on the server.
  • Self-contained: the runtime travels with the application. Bigger package, but no dependency on the server: ideal on shared hosting.
dotnet publish -c Release -r win-x64 --self-contained true -o ./publish

In-process

With the in-process model the application runs inside the IIS process: it is the fastest. The web.config file generated by publishing tells the ASP.NET Core module which executable to start.

Updating without locked files

Copying an app_offline.htm file into the site folder makes the module stop the application and show that page: you replace the DLLs and then remove the file. Before removing it, check that the copied files are complete.

When 500.30 appears

Error 500.30 means the application was started but failed during startup. To find out where:

  1. Enable stdout logs in web.config (stdoutLogEnabled="true") in a writable folder.
  2. Write a log to file as the very first statement of Program.cs: if it does not appear, the problem is before your code.
  3. For runtime loading problems, the COREHOST_TRACE environment variable produces a detailed host trace.

A lesson about dependencies

Removing a NuGet package can change the version of libraries that came in indirectly through that package, and therefore the binary produced. Before every release compare the deps.json file and the DLL's references with the version in production, and if needed pin the versions of transitive dependencies explicitly in the project.


Containers for .NET apps without a Dockerfile

Writing and maintaining a Dockerfile for every .NET project is no longer necessary: the SDK can build the image by itself, using the project's information.

The SDK builds the image with no Dockerfile to maintain.
The SDK builds the image with no Dockerfile to maintain.

One command

dotnet publish -c Release --os linux --arch x64 -t:PublishContainer

The result is an image in the local container engine, named after the project. For web applications it works with no configuration; for console applications you enable it with the EnableSdkContainerSupport property.

Customising the image

<PropertyGroup>
  <ContainerRepository>company/catalog-api</ContainerRepository>
  <ContainerImageTags>1.4.0;latest</ContainerImageTags>
  <ContainerFamily>noble-chiseled</ContainerFamily>
</PropertyGroup>

Chiseled images contain only the bare minimum needed to run the application: no shell, no package manager. They are smaller and offer far less attack surface.

Secure by default

Recent .NET images run the application as a non-privileged user and the default port is 8080, which does not require administrator permissions. These choices reduce the damage in case of a vulnerability.

Publishing to a registry

dotnet publish -c Release -t:PublishContainer \
  -p:ContainerRegistry=registry.company.com \
  -p:ContainerRepository=catalog-api

In continuous integration pipelines this removes a whole step: no Docker to install on the build agent to create the image, and the configuration lives in the project file, versioned together with the code.


Observability in .NET: OpenTelemetry and health checks

When a user reports "the site is slow", you need data, not guesses. OpenTelemetry is the open standard for collecting traces, metrics and logs, and .NET supports it natively.

An open standard: you change monitoring system without touching code.
An open standard: you change monitoring system without touching code.

Basic configuration

builder.Services.AddOpenTelemetry()
    .ConfigureResource(r => r.AddService("shop-api"))
    .WithTracing(t => t
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation())
    .WithMetrics(m => m
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddRuntimeInstrumentation())
    .UseOtlpExporter();

Data is sent over the OTLP protocol to any compatible system: open-source solutions, cloud services or the Aspire dashboard during development.

Custom traces

public static class Telemetry
{
    public static readonly ActivitySource Source = new("Shop.Orders");
}

using var activity = Telemetry.Source.StartActivity("ComputeShipping");
activity?.SetTag("order.country", order.Country);

Health checks

A health endpoint tells load balancers, orchestrators and monitoring systems whether the instance is ready to receive traffic.

builder.Services.AddHealthChecks()
    .AddCheck("disk-space", () =>
    {
        var free = new DriveInfo(AppContext.BaseDirectory).AvailableFreeSpace;
        return free > 500_000_000
            ? HealthCheckResult.Healthy()
            : HealthCheckResult.Degraded("Disk space running low");
    });

app.MapHealthChecks("/health");

What to really measure

Response times per endpoint, error rate, duration of queries and external calls. A few well-chosen indicators, with sensible alert thresholds, are worth more than a hundred charts nobody looks at.


Aspire: orchestrating distributed applications in development

A modern application is rarely a single project: an API, a frontend, a database, a cache, perhaps a queue. Starting them all, wiring them up and understanding what happens between them is tiring. Aspire (born as .NET Aspire) solves exactly this.

The AppHost starts and connects every resource, the dashboard observes them.
The AppHost starts and connects every resource, the dashboard observes them.

The AppHost

A special project describes in C# the application's resources and how they are connected:

var builder = DistributedApplication.CreateBuilder(args);

var cache = builder.AddRedis("cache");
var db = builder.AddPostgres("postgres").AddDatabase("catalog");

var api = builder.AddProject<Projects.Catalog_Api>("api")
    .WithReference(db)
    .WithReference(cache);

builder.AddProject<Projects.Shop_Web>("web")
    .WithReference(api);

builder.Build().Run();

At startup Aspire creates the necessary containers, passes connection strings and service addresses to the projects, and opens a dashboard.

The dashboard

Logs, distributed traces and metrics for every service in a single interface. You can watch a request travel through frontend, API and database, with the timing of each step: finding a bottleneck becomes a matter of minutes.

Service defaults

A shared project applies the same baseline settings to every service: OpenTelemetry, health checks, HTTP call resilience and service discovery. Each project enables it with one line, builder.AddServiceDefaults().

And in production?

Aspire is mainly designed for local development, but the application model can be used to generate deployment configuration for containers and the cloud. Even without using it in production, the gain during development and integration testing is significant.


Resilient HttpClient in .NET: retry, timeout and circuit breaker

Every call to an external service can fail: unstable network, overloaded server, timeouts. A robust application accounts for this from the start.

Every call goes through the layers in order, from outside in.
Every call goes through the layers in order, from outside in.

IHttpClientFactory

Creating a new HttpClient for every call exhausts connections; keeping a single one forever ignores DNS changes. The factory handles both and is the recommended approach.

builder.Services.AddHttpClient<WeatherClient>(c =>
{
    c.BaseAddress = new Uri("https://api.weather.example/");
    c.Timeout = TimeSpan.FromSeconds(30);
})
.AddStandardResilienceHandler();

The standard resilience handler

The Microsoft.Extensions.Http.Resilience package adds, in one line, a well-designed pipeline: concurrency limiter, total timeout, retry with increasing randomised delay, circuit breaker and per-attempt timeout. The values can be tuned:

.AddStandardResilienceHandler(o =>
{
    o.Retry.MaxRetryAttempts = 3;
    o.AttemptTimeout.Timeout = TimeSpan.FromSeconds(5);
    o.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(20);
});

The typed client

public class WeatherClient(HttpClient http)
{
    public Task<Forecast?> TodayAsync(string city, CancellationToken ct) =>
        http.GetFromJsonAsync<Forecast>($"forecasts/{Uri.EscapeDataString(city)}", ct);
}

Be careful with retries

Repeating a read is safe; repeating a payment is not. Operations that modify data should only be retried if they are idempotent, for example thanks to an idempotency key sent to the server. And when the external service is down for a long time, the circuit breaker stops hammering it and returns a manageable error immediately.


Structured logging in .NET with LoggerMessage

A good log entry is not a sentence: it is an event with queryable data. ILogger supports structured logging, which keeps the text and the values separate.

Values stay queryable fields, not text to search.
Values stay queryable fields, not text to search.

Placeholders, not interpolation

// Avoid: the value is lost inside the string, and the string is always built
log.LogInformation($"Order {order.Id} created by {user}");

// Correct: Id and User stay separate, queryable fields
log.LogInformation("Order {OrderId} created by {User}", order.Id, user);

In log collection systems you can then search for "all events with OrderId = 4521" instead of searching text.

LoggerMessage: logs generated at compile time

For frequent log entries, the LoggerMessage attribute generates optimised methods that avoid allocations and check at compile time that placeholders match the parameters.

public static partial class Log
{
    [LoggerMessage(EventId = 1001, Level = LogLevel.Information,
        Message = "Order {OrderId} created for {Amount} euros")]
    public static partial void OrderCreated(this ILogger logger, int orderId, decimal amount);

    [LoggerMessage(EventId = 1002, Level = LogLevel.Warning,
        Message = "Payment declined for order {OrderId}: {Reason}")]
    public static partial void PaymentDeclined(this ILogger logger, int orderId, string reason);
}

log.OrderCreated(order.Id, order.Total);

Levels and noise

  • Information for meaningful business events.
  • Warning for unusual but handled situations.
  • Error for failed operations, always with the exception as the first argument.
  • Debug for details, disabled in production.

And never personal data or secrets in logs: passwords, tokens and sensitive data must not end up in a file that many people can read.


Configuration in .NET: the Options pattern and validation at startup

Reading configuration with strings scattered around the code leads to typos discovered only in production. The Options pattern turns a configuration section into a typed, validated class.

With ValidateOnStart a wrong configuration stops startup, not production.
With ValidateOnStart a wrong configuration stops startup, not production.

The settings class

public class SmtpOptions
{
    [Required] public string Host { get; set; } = "";
    [Range(1, 65535)] public int Port { get; set; } = 587;
    [Required, EmailAddress] public string Sender { get; set; } = "";
}
{
  "Smtp": { "Host": "smtp.company.com", "Port": 587, "Sender": "noreply@company.com" }
}

Registration with validation at startup

builder.Services.AddOptions<SmtpOptions>()
    .BindConfiguration("Smtp")
    .ValidateDataAnnotations()
    .ValidateOnStart();

With ValidateOnStart the application does not start if the configuration is wrong: a clear error at deploy time beats an unsent email at three in the morning.

IOptions, IOptionsSnapshot or IOptionsMonitor?

  • IOptions<T>: values read once, ideal for settings that do not change.
  • IOptionsSnapshot<T>: recomputed on every request, useful if the configuration file can change at runtime.
  • IOptionsMonitor<T>: current value plus change notifications, suited to singletons.

Secrets

Passwords and keys do not belong in the configuration file saved in the repository: in development use user secrets, in production environment variables or a secrets store. The Options pattern does not change: it reads from all these sources in the same way.


Dependency Injection in .NET: lifetimes and keyed services

The dependency injection container built into .NET covers the vast majority of cases. Knowing its lifetimes and newest features well avoids bugs that are hard to track down.

A service must never depend on one with a shorter lifetime than its own.
A service must never depend on one with a shorter lifetime than its own.

The three lifetimes

  • Singleton: a single instance for the whole application. It must be thread-safe.
  • Scoped: one instance per web request (or per manually created scope).
  • Transient: a new instance every time it is requested.

The classic mistake is injecting a scoped service into a singleton: the singleton holds on to it forever, sharing for example a database context across different requests. In the development environment .NET reports this at startup.

Keyed services

When you need several implementations of the same interface, register them with a key:

builder.Services.AddKeyedSingleton<INotifier, EmailNotifier>("email");
builder.Services.AddKeyedSingleton<INotifier, SmsNotifier>("sms");

public class AlertService(
    [FromKeyedServices("email")] INotifier email,
    [FromKeyedServices("sms")] INotifier sms)
{
    public Task UrgentAsync(string text) =>
        Task.WhenAll(email.SendAsync(text), sms.SendAsync(text));
}

In Minimal APIs the same attribute is used on handler parameters.

Background services and scopes

A BackgroundService is a singleton. To use scoped services, such as a repository, you create an explicit scope:

public class CleanupService(IServiceScopeFactory scopes) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        using var timer = new PeriodicTimer(TimeSpan.FromHours(1));
        while (await timer.WaitForNextTickAsync(ct))
        {
            using var scope = scopes.CreateScope();
            var repo = scope.ServiceProvider.GetRequiredService<ILogRepository>();
            await repo.DeleteOldAsync(ct);
        }
    }
}

Rule of thumb: register as singleton only what is truly shareable and free of per-user state, and keep everything that touches request data scoped.


Comments (0)

No comments yet.

Leave a comment