Search code examples
c#.netconfigurationaot

Why doesn't strongly typed Configuration work with AOT


I am trying to add configuration to my console app via appsettings.json with a connection settings object

public class ConnectionSettings
{
    public string IP { get; set; } = string.Empty;
    public string Port { get; set; } = string.Empty;
    public string Username { get; set; } = string.Empty;
    public string Password { get; set; } = string.Empty; 
}

and my app:

var builder = Host.CreateApplicationBuilder(args);

builder.Services.Configure<ConnectionSettings>(builder.Configuration.GetSection(nameof(ConnectionSettings)));
builder.Services.AddHostedService<Executer>();

var app = builder.Build();
app.Run();

This works fine with not AOT but with AOT enabled I get warnings about code generation at runtime which AOT cannot do.

So is there a way to be able to add this kind of configuration to my DI when using AOT?


Solution

  • Assuming you are using or can upgrade to it:

    As per the What's new in the .NET 8 runtime: Configuration-binding source generator:

    .NET 8 introduces a source generator to provide AOT and trim-friendly configuration in ASP.NET Core. The generator is an alternative to the pre-existing reflection-based implementation.

    It's enabled by default in AOT-compiled web apps, and when PublishTrimmed is set to true (.NET 8+ apps). For other project types, the source generator is off by default, but you can opt in by setting the EnableConfigurationBindingGenerator property to true in your project file

    So add the following to your csproj file (though my test app actually worked without using this setting):

    <PropertyGroup>
        <EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>
    </PropertyGroup>