Environment – is exactly the place, where you gonna be store such variables as connections string, different usernames for authorisations in external systems, ports, number settings and etc.
Dotnet framework provides special interface for working with env files and, also, special secured container for more sensible and secured information called user-secrets
.
Adding secrets to project
1 2 3 |
dotnet user-secrets init dotnet user-secrets set "Redis:ConnectionString" "12345" |
Accessing configuration (for secrets – similar)
1 2 3 4 5 6 7 |
IConfiguration configuration; // with get Configuration.GetSection("Redis") // indexed key style Configuration["Redis:ConnectionString"] |
Mapping configuration to POCO
1 |
var moviesConfig = Configuration.GetSection("Redis").Get<RedisOptions>(); |
Accessing configuration object through Dependency Injection
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class RedisOptions { public string ConnectionString {get; set;} //... } // binding configuration section to runtime object services.Configure<RedisOptions>("Redis"); // Accessing anywhere in constructor through DependencyInjection class Controller { public Controller(IOptions<JwtSettingsDto> jwtOptions) { //... } } |
Accessing connection string
1 |
Configuration.GetConnectionString("DefaultConnectionString"); |