Last active
September 22, 2018 22:18
-
-
Save MirzaMerdovic/4adabe46134bd15d347234154193f88b to your computer and use it in GitHub Desktop.
Snippeet for injecting reloadable strongly typed configuration into your asp.net core Web API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Let's say that your appsettings.{envinronment}.json looks like this. | |
``` | |
{ | |
"DatabaseConfiguration": { | |
"apiDb": "Server={localhost};Initial Catalog={database};User ID={userName};Password={password};", | |
"api2Db": "Server={localhost};Initial Catalog={database};User ID={userName};Password={password};" | |
}, | |
} | |
``` | |
To achive a strongly typed injectable configuration you will need this. | |
1. Create a POCO class that maps to your appsettings (desired section, it doesn't have to be the whole file) | |
``` | |
namespace CoreStarter.Api.Configuration | |
{ | |
public class ConnectionStrings | |
{ | |
public string ApiDb { get; set; } | |
public string Api2Db { get; set; } | |
} | |
} | |
``` | |
2. Startup configuration | |
``` | |
public IServiceProvider ConfigureServices(IServiceCollection services) | |
{ | |
IConfigurationRoot configuration = | |
new ConfigurationBuilder() | |
.SetBasePath(_env.ContentRootPath) | |
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) | |
.AddJsonFile($"appsettings.{_env.EnvironmentName}.json", optional: true, reloadOnChange: true) | |
.AddEnvironmentVariables() | |
.Build(); | |
services.Configure<ConnectionStrings>(configuration.GetSection("ConnectionStrings")); | |
} | |
``` | |
3. Inject it | |
``` | |
public FooController(IOptionsSnapshot<ConnectionStrings> connectionStrings, IFooService service, ILogger<FooController> logger) | |
{ | |
_connectionStrings = connectionStrings.Value ?? throw new ArgumentNullException(nameof(connectionStrings)); | |
_service = service ?? throw new ArgumentNullException(nameof(service)); | |
_logger = logger ?? throw new ArgumentNullException(nameof(logger)); | |
} | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment