Search code examples
c#asp.netenvironment-variablessingleton

ASP.Net access enviroment variables in singleton class


i need to access my enviroment variables from a singleton class.

I only found soulutions where the WebBuilder injects the configuration through the constructor or methods to a PageModel.

Singleton Class

public class GraphQLAPI
{
    public static GraphQLAPI Instance { 
        get 
        {
            if (_instance == null)
                _instance = new GraphQLAPI();

            return _instance;
        } 
    }
    private static GraphQLAPI _instance;
    private GraphQLAPI() 
    {
        
        _qlClient = new GraphQLHttpClient("XXX", new SystemTextJsonSerializer());
        _qlClient.HttpClient.DefaultRequestHeaders.Add("Authorization", "XXX");
    }
    [...]
}

Is it even possible? If not, is there another way to pass the value to my client?


Solution

  • I just created 2 static fields in the GraphQLAPI.cs which will be set in the Startup.cs

    GraphQLAPI.cs

    public class GraphQLAPI
    {
        public static string GraphQLHostUrl { get; set; }
        public static string GraphQLAuthorization { get; set; }
    
        [...]
        private GraphQLAPI() 
        {
            
            _qlClient = new GraphQLHttpClient(GraphQLHostUrl, new SystemTextJsonSerializer());
            _qlClient.HttpClient.DefaultRequestHeaders.Add("Authorization", GraphQLAuthorization);
        
        }
        [...]
    }
    

    Startup.cs

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            GraphQLAPI.GraphQLHostUrl = configuration.GetValue<string>("GraphQlUrl");
            GraphQLAPI.GraphQLAuthorization = configuration.GetValue<string>("ApiAuthorization");
        }
        [...]
    }