C# by Doug

Add IConfiguration to the service collection

To add IConfiguration to the service collection, you can use the IServiceCollection interface. First, create a ServiceCollection instance, then use the AddSingleton method to add IConfiguration, passing in your configuration object _config.

IConfigurationBuilder builder = new ConfigurationBuilder()
    .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
    .AddJsonFile("appsettings.json");

IConfiguration configuration = builder.Build();

IServiceCollection services = new ServiceCollection();
services.AddSingleton<IConfiguration>(configuration);

This setup is particularly useful for scenarios like unit testing background services, as discussed in this Stack Overflow thread: Unit testing a .NET Core background service.

Comments