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
.
So no need to inject IConfiguration
any more, it is now a property in the builder
in Program.cs.
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
No Console Output When Using Allocconsole and Target Architecture X86
How to Get the Last Five Characters of a String Using Substring() in C#
How to Bind Parameters via Odbc C#
Datetime Conversion from String C#
Httpwebrequest Is Extremely Slow!
How Do C# Events Work Behind the Scenes
How to Merge 2 List<T> and Removing Duplicate Values from It in C#
How to Read All Files Inside Particular Folder
How to Serialize an Exception Object in C#
Windows 7 and Vista Uac - Programmatically Requesting Elevation in C#
How to Use Httpclient to Send Content in Body of Get Request
Lambda Expression Not Returning Expected Memberinfo
What's the Difference Between Returning Void and Returning a Task
Save and Retrieve Image (Binary) from SQL Server Using Entity Framework 6
How to Do Network Discovery Using Udp Broadcast
How to Convert Datetime To/From Specific String Format (Both Ways, E.G. Given Format Is "Yyyymmdd")