In this lesson, you will learn how to decouple sensitive secrets from your application code by leveraging the IConfiguration provider to inject values directly from container environment variables.
The Problem with Hardcoding
As you move into production-ready containerized architectures, hardcoding connection strings or API keys is a significant security vulnerability. Even if you don't commit these to source control, they remain baked into the container image layers, accessible to anyone with access to the image registry. Instead, we use environment variables as the source of truth, treating the container as an immutable unit that adapts to its environment.
Integrating with .NET Configuration
The .NET ConfigurationBuilder is designed to automatically aggregate configuration from multiple sources. When running in a container, the default host configuration looks for environment variables automatically.
Consider a scenario where you need a DatabaseConnectionString. Rather than hardcoding it, define it in your appsettings.json as a fallback, and override it via an environment variable in your deployment manifest:
// In your Program.cs, no special code is required to read the variable
// .NET automatically maps environment variables to your IConfiguration
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
Secure Injection Patterns
In a production orchestrator like Kubernetes, you inject these secrets at runtime using Secret objects mapped as environment variables. Because .NET's AddEnvironmentVariables() provider (included by default in CreateDefaultBuilder) reads these into the IConfiguration object, your application code remains agnostic to whether the value came from a file or the host system.
Crucial Best Practice: When naming your environment variables, use double underscores (__) to denote hierarchical configuration. For example, setting an environment variable named ConnectionStrings__DefaultConnection will correctly map to the ConnectionStrings:DefaultConnection key in your .NET configuration system. This allows you to map complex, nested configuration objects from flat environment variable structures without changing a single line of your application logic.
Key Takeaway: Never store secrets in your source code; use the .NET Configuration provider to bridge environment variables into your application, ensuring your container images remain secret-free and portable across environments.