How to Add IConfiguration to a Custom ServiceProvider

IConfiguration is included as the default builder setting when using ASP.Net Core Web host or .NET Generic Host. Making access to app config settings by default available through dependency injection wherever in your app.

But, consider this alternative approach to build and run a console app where the app is a service by itself

internal class Program
{
    static async Task Main(string[] args)
    {
        var services = CreateServices();
        ConsoleApp app = services.GetRequiredService<ConsoleApp>();             
        await app.Run();
    }
    private static ServiceProvider CreateServices()
    {
        var serviceProvider = new ServiceCollection()
            .AddLogging(options =>
            {
                options.ClearProviders();
                options.AddConsole();
            })            
            .AddSingleton<ImportService>()
            .AddSingleton<ConsoleApp>()                
            .BuildServiceProvider();
        return serviceProvider;
    }
}

When using this alternative approach, there will be no default builder settings, making IConfiguration (and thus access to app config settings) unavailable through dependency injection.

To arrange this, the CreateServices() method is extended as follows.

private static ServiceProvider CreateServices()
{
    // Use Configuration builder to build and configure            
    var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
    // a configuration object
    IConfiguration configuration = builder.Build();                
    var serviceProvider = new ServiceCollection()
        .AddLogging(options =>
        {
            options.ClearProviders();
            options.AddConsole();
        })
        //Use the configuration object to configure IConfiguration
        //as a service in the service collection
        .AddSingleton<IConfiguration>(_ => configuration)
        .AddSingleton<ImportService>()
        .AddSingleton<ConsoleApp>()                
        .BuildServiceProvider();
    return serviceProvider;
}

With this adjustment, it will be possible to access app config settings by simply adding IConfguration as a parameter to the constructor of the class where you want to use it.

public ImportService(IConfiguration configuration, ILogger<ImportService> logger)
{
    this._logger = logger;
    this._configuration = configuration;    
}