Environment Variables and Secrets in .NET Core: Best Practices
- Published on
- • 1 mins read•--- views
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
dotnet user-secrets init
dotnet user-secrets set "Redis:ConnectionString" "12345"
Accessing configuration (for secrets - similar)
IConfiguration configuration;
// with get
Configuration.GetSection("Redis")
// indexed key style
Configuration["Redis:ConnectionString"]
Mapping configuration to POCO
var moviesConfig = Configuration.GetSection("Redis").Get<RedisOptions>();
Accessing configuration object through Dependency Injection
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
Configuration.GetConnectionString("DefaultConnectionString");
Related
Posts
How to Move Changes to Another Branch in Visual Studio TFS (tfpt unshelve)
A practical guide for developers: how to move your pending changes to another branch in Visual Studio Team Foundation Server using tfpt unshelve, with step-by-step instructions and screenshots.
Project Structure and Testing in .NET Core 6 vs .NET Core 5: Unit Tests, GraphQL, and Test Server Fixtures
A practical comparison of .NET Core 5 and 6 project structures, with real-world examples for unit testing, GraphQL integration, and test server fixture setup.
C# Unit Testing with Moq: Verifying Method Calls and Exceptions
A practical guide to using the Moq library for unit testing in C#, including how to verify method calls, handle exceptions, and test logging logic.
Open for contract collaboration
I am available for contract-based collaboration. If you have an interesting project idea, schedule a call via Calendly.
Schedule a 30-min call