How to Access Configuration in Any Class in ASP.NET Core

How do I access Configuration in any class in ASP.NET Core?

Update

Using ASP.NET Core 2.0 will automatically add the IConfiguration instance of your application in the dependency injection container. This also works in conjunction with ConfigureAppConfiguration on the WebHostBuilder.

For example:

public static void Main(string[] args)
{
var host = WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(builder =>
{
builder.AddIniFile("foo.ini");
})
.UseStartup<Startup>()
.Build();

host.Run();
}

It's just as easy as adding the IConfiguration instance to the service collection as a singleton object in ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfiguration>(Configuration);

// ...
}

Where Configuration is the instance in your Startup class.

This allows you to inject IConfiguration in any controller or service:

public class HomeController
{
public HomeController(IConfiguration configuration)
{
// Use IConfiguration instance
}
}

.Net Core How to Access Configuration Anywhere in application

I would say that in .Net Core application you shouldn't pass instance of IConfiguration to your controllers or other classes. You should use strongly typed settings injected through IOtions<T> instead. Applying it to your case, modify MyConfig class (also property names should match names in config, so you have to rename either config (DefaultConnection->DefaultConnStr, AW2012ConnStr->AWConnStr or properies vice versa):

public class MyConfig
{
public string AWConnStr { get; set; }
public string DefaultConnStr { get; set; }
}

Register it:

public void ConfigureServices(IServiceCollection services)
{
// in case config properties specified at root level of config file
// services.Configure<MyConfig>(Configuration);

// in case there are in some section (seems to be your case)
var section = Configuration.GetSection("ConnectionStrings");
services.Configure<MyConfig>(section);
}

Inject it to required service:

public class MyService
{
private readonly MyConfig _settings;

public MyService(IOptions<MyConfig> options)
{
_settings = options.Value;
}
}

And what's the difference between services.AddTransient and
services.AddScoped? I've seen both as a way to register the service.

Transient lifetime services are created each time they're requested.

Scoped lifetime services are created once per request.

ASP.NET Core 6 how to access Configuration during startup

WebApplicationBuilder returned by WebApplication.CreateBuilder(args) exposes Configuration and Environment properties:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
...
ConfigurationManager configuration = builder.Configuration; // allows both to access and to set up the config
IWebHostEnvironment environment = builder.Environment;

WebApplication returned by WebApplicationBuilder.Build() also exposes Configuration and Environment:

var app = builder.Build();
IConfiguration configuration = app.Configuration;
IWebHostEnvironment environment = app.Environment;

Also check the migration guide and code samples.

How to inject IConfiguration in asp.net core 6

The IConfiguration can be accessed in the WebApplicationBuilder.

Sample Image

So no need to inject IConfiguration any more, it is now a property in the builder in Program.cs.
Sample Image

var builder = WebApplication.CreateBuilder(args);
var config = builder.Configuration;

builder.Services.AddInfrastructureServices(config);
builder.Services.AddPersistenceServices(config);

How to use appsettings.json in Asp.net core 6 Program.cs file

While the examples above work, the way to do this is the following:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = builder.Configuration["Redis"];
});

The WebApplicationBuilder has a configuration object as a property that you can use.

Access Configuration from a View in ASP.NET Core

In asp.net core , you can inject IConfiguration implementation to your views and use that :)

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
<link rel="stylesheet" href="@Configuration["MyConfigEntry"]/css/site.min.css">

Access Configuration/Settings on static class - Asp Core

I feel like this may be more work than necessary, but I'm in a rush so this is what I'm going with so far. Feel free to post other solutions as they become available.

I create another static class AppSettingsProvider.cs

public static class AppSettingsProvider
{
public static string DbConnectionString { get; set; }
public static bool IsDevelopment { get; set; }
}

Then I set them on my Startup.cs

public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();

BuildAppSettingsProvider();
}
private void BuildAppSettingsProvider()
{
AppSettingsProvider.ConnectionString = Configuration.GetConnectionString("DBContext");
AppSettingsProvider.IsDevelopment = Configuration["IsDev"];
}

Then I can call it from my DbContext.cs

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string connString = AppSettingsProvider.ConnectionString;
}

P.S. I tried the dependency injection method into DbContext (by having contructors). However, that did not work for me because I was calling DbContext from a static file, so the DbContextOptions was getting lost.



Related Topics



Leave a reply



Submit