Home > other >  Get configuration values in any class without dependency injection
Get configuration values in any class without dependency injection

Time:12-06

I'm trying to access a configuration value declared in appsettings.json in any class of the project. I found various ways to do this using 'dependency injection' but that doesn't help me out. So what I have so far is to validate a boolean from appsettings.json to be true in a validator. This is used as backend for a React Typescript project

This is what I have on Startup.cs

services.Configure<RequestLocalizationOptions>(options => {
    options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("ro-RO");
    options.SupportedCultures = new []{ new CultureInfo("ro-RO"), new CultureInfo("en") };
    options.SupportedUICultures = new []{ new CultureInfo("ro-RO"), new CultureInfo("en") };
});

...

services.AddCore(Configuration);
services.AddDataAccess(Configuration);

And this is on Programs.cs

public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
    .Build();

public static void Main(string[] args) {

    Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(Configuration)
        .Enrich.FromLogContext()
        .CreateLogger();
            
    try {
        CreateWebHostBuilder(args).Build().Run();
    } catch (Exception ex) {
        Log.Fatal(ex, "Host terminated unexpectedly");
    } finally {
        Log.CloseAndFlush();
    }
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseConfiguration(Configuration)
        .UseSerilog();

Tried declaring configuration file into my other class but with no success. Also tried creating a new instance of configuration in my class, also a failure.

CodePudding user response:

Here is an example of how you can access a configuration value declared in appsettings.json in any class of the project:

In your Startup.cs file, inject an instance of IConfiguration into the Startup class' constructor:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // Rest of the Startup class goes here
}

In your ConfigureServices method, add the configuration instance to the service container so that it can be accessed by other classes in your project:

public void ConfigureServices(IServiceCollection services)
{
    // Other service configuration goes here

    services.AddSingleton(Configuration);
}

In any class where you want to access the configuration values, you can inject an instance of IConfiguration using constructor injection:

public class MyClass
{
    private readonly IConfiguration _configuration;

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

    public void DoSomething()
    {
        // Access configuration values here
        bool myValue = _configuration.GetValue<bool>("MyKey");
    }
}

You can then use the _configuration instance to access values from your appsettings.json file.

Alternatively, you can use the built-in IOptions<T> pattern in ASP.NET Core to bind specific configuration values to a strongly-typed options class. This can make it easier to access and use configuration values in your code.

  • Related