dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.41k stars 4.76k forks source link

[API Proposal]: Like WebApplicationBuilder allow us to put a finished IConfiugration instance into a HostBuilder #110051

Open drauch opened 15 hours ago

drauch commented 15 hours ago

For internal reasons we create and validate the IConfiguration instance before building hosts. The .NET 6 WebApplicationBuilder lets us register this instance directly at the container:

var builder = WebApplicationBuilder.CreateBuilder();
OurConfigurationUtility.SetUp(builder.Configuration);

builder.Services.AddSingleton<IConfiguration>(builder.Configuration);

var startup = new Startup(builder.Configuration);
startup.ConfigureServices(builder.Services);

var app = builder.Build();

startup.Configure(app, app.Environment);

app.Run();

However, for our non-web background services we can't do the same with HostBuilder. To our knowledge there is only the ConfigureAppConfiguration method which already puts in some defaults and lets you work with a ConfigurationBuilder but there is no way to put a finished IConfiguration instance in, is there?

Best regards, D.R.

dotnet-policy-service[bot] commented 15 hours ago

Tagging subscribers to this area: @dotnet/area-extensions-configuration See info in area-owners.md if you want to be subscribed.

julealgon commented 12 hours ago

You should still be able to register your own singleton instance the exact same way using ConfigureServices:

.ConfigureServices((context, services) =>
{
    OurConfigurationUtility.SetUp(context.Configuration);

    services.AddSingleton<IConfiguration>(context.Configuration);
})

I'm just confused by your usage there... you pass in the configuration, and then your method does mutations to it? Regardless... I believe the above should still work, although I'm not sure whether that registration will be overridden by the Host.Build() call later.

Why do you have this external configuration method in the first place?

tarekgh commented 10 hours ago

Can't you do something like:

hostBuilder.ConfigureAppConfiguration((context, config) =>
{
    config.Sources.Clear(); // Clear existing configuration sources
    // then add your configuration the config
});
dotnet-policy-service[bot] commented 10 hours ago

This issue has been marked needs-author-action and may be missing some important information.