'How to resolve repository without BuilderServiceProvider in ConfigureService?

I need to load list from repository in ConfigureService method, not in Configure method. I loop list to generate multiple authentication scheme.

This is my method to load my list, it's works but I've Warning about builder.Services.BuildServiceProvider();.

Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'.

var listCarrierSetting = GetCarrierSetting();

List<Setting> GetCarrierSetting()
{
    List<Setting> result = new();

    try
    {
        var sp = builder.Services.BuildServiceProvider();
        
        var settingRepository = sp.GetRequiredService<ISettingRepository>();

        var task = Task.Run(async () => await settingRepository.GetAllWithDetails());
        
        result = task.Result as List<Setting>;
    }
    catch (Exception)
    {
        //some code
    }

    return result;
}

Is it possible to resolve and call my repository without use BuildServiceProvider() ?



Solution 1:[1]

ConfigureServices is the place to register the services in the service provider and - as the error message says - it should not build the service provider prematurely.

However, you can rely on the configuration in ConfigureServices. So an option is to move the settings for the authentication schemes to application configuration. You can use a built-in configuration provider (e.g. for appsettings.json, environment variables, ...) and store the settings in the respective location.

If these do not work for your requirements, you can also create a custom configuration provider as described here. The sample also shows how to use a temporary config that contains a connection string for connecting to the database.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Markus