Validate the Dependency Injection Configuration at Build Time

By default, ASP.NET validates the dependency injection container configuration at runtime. As a result, we only discover missing or misconfigured dependencies when the application runs. While this approach works, getting feedback at the build time would be a time saver.

Starting with .NET 8, we can enable build-time validation by activating the ValidateOnBuild property in our service configuration:

using System;
using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();

// Register services with an intentional error:
// Baz is required but never registered.
services.AddTransient<Foo>();
services.AddTransient<Bar>();

try
{
    var serviceProvider = services.BuildServiceProvider(
        new ServiceProviderOptions
        {
            ValidateOnBuild = true,
            ValidateScopes = true
        });
}
catch (Exception ex)
{
    Console.WriteLine("DI validation failed at build time:");
    Console.WriteLine(ex.Message);
}

public class Foo
{
    public Foo(Bar bar) { }
}

public class Bar
{
    public Bar(Baz baz) { }
}

public class Baz
{
}

When we build the application, the framework now validates the configuration immediately and reports any issues. In the code above we did not define how to create Baz(), so the build fails and we get this error message:

DI validation failed at build time:

Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Foo Lifetime: Transient ImplementationType: Foo': Unable to resolve service for type 'Baz' while attempting to activate 'Bar'.) (Error while validating the service descriptor 'ServiceType: Bar Lifetime: Transient ImplementationType: Bar': Unable to resolve service for type 'Baz' while attempting to activate 'Bar'.)

If you want faster feedback, activate the ValidateOnBuild option.