ShaneKm
ShaneKm

Reputation: 21328

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?

Upvotes: 3

Views: 8897

Answers (1)

Set
Set

Reputation: 49779

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));

Upvotes: 7

Related Questions