1

How can I use IConfiguration to initialize singleton?

public class Singleton
{
    Singleton(string apiKey)
    {
        this.apiKey = apiKey;
    }
    private static readonly object instanceGeneratorLock = new object();
    private static Singleton instance = null;
    private readonly string apiKey;
    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (instanceGeneratorLock)
                {
                    if (instance == null)
                    {
                        /* use IConfiguration here */
                        var apiKey = System.Configuration.ConfigurationManager.AppSettings["ApiKey"];                            
                        instance = new Singleton(apiKey);
                    }
                }
            }
            return instance;
        }
    }
}
2
  • 1
    don't use "static property + private constructor" singleton, use DI singleton Commented Jul 7, 2020 at 5:41
  • Your approach is not good. Injecting IConfiguration in this context is actually an anti-pattern. You should send to constructor only the parameters you need. This article should bring you the extra clarifications. Commented Jul 7, 2020 at 6:15

1 Answer 1

3

Instead of manually creating the singleton and using it like regularly, I'd recommend you use a dependency injected singleton. This is very easy to achieve and can be done like so, inside your ConfigureServices method of Startup.cs:

services.AddSingleton(typeof(Singleton));

This will register your Singleton which will from then on forwards be able to be injected into any other class constructed via dependency injection (DI).
There are multiple overloads for this, for different use cases, all documented here

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.