Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject .NET Core IConfiguration into Singleton

I have the following Singleton class that I would like to use throughout my app:

public sealed class AppSettings
{
    private static readonly Lazy<AppSettings> _lazy =
        new Lazy<AppSettings>(() => new AppSettings());

    private AppSettings()
    {
        // I want to inject this
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true);

        Config = builder.Build();
    }

    public static AppSettings Instance => _lazy.Value;

    public IConfigurationRoot Config { get; }
}

I would like to inject IConfiguration instead of having it built within it. How can I do this?

like image 610
ShaneKm Avatar asked Dec 08 '25 17:12

ShaneKm


1 Answers

You don't need to create your own singleton class. Instead, create a normal class and register/add it to DI container as singleton:

public sealed class AppSettings
{
    private IConfiguration _configuration;

    public AppSettings(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    ...
}

and then in ConfigureServices method just use

// IConfigurationRoot ConfigureServices;

services.AddSingleton(new AppSettings(Configuration));
like image 160
Set Avatar answered Dec 12 '25 04:12

Set



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!