Search code examples
c#.net-8.0

How to configure ServiceProviderOptions with HostApplicationBuilder instead of HostBuilder with .NET Generic Host?


What i'm doing :

In a console application (not related to ASP.NET) I'm using the .NET Generic Host template in .NET 8.
I can force service provider options with UseDefaultServiceProvider extension method on IHostBuilder created with Host.CreateDefaultBuilder() :

IHostBuilder builder = Host.CreateDefaultBuilder(args);
builder.UseDefaultServiceProvider((ServiceProviderOptions opt) =>
{
    opt.ValidateOnBuild = true;
    opt.ValidateScopes = true;
});

What I want to do :

There's a new method Host.CreateApplicationBuilder() that returns an IHostApplicationBuilder (https://learn.microsoft.com/en-us/dotnet/core/extensions/generic-host?tabs=appbuilder#set-up-a-host). I would like to use it, but there are no similar extensions methods on this interface and I found no way to access ServiceProviderOptions.


Solution

  • Mentioned above, but here is the answer:

    var app = Host.CreateApplicationBuilder();
    app.ConfigureContainer(new DefaultServiceProviderFactory(new ServiceProviderOptions
    {
        ValidateOnBuild = false,
        ValidateScopes = true
    }));