Olson CloudWorks 🚀

How do I access Configuration in any class in ASPNET Core

September 19, 2026

📂 Categories: C#
How do I access Configuration in any class in ASPNET Core

In modern ASP.NET Core development, managing application configuration is crucial for creating flexible and maintainable applications. The configuration system in ASP.NET Core allows you to store and retrieve settings from various sources such as JSON files, environment variables, and command-line arguments. Knowing how to access Configuration in any class in ASP.NET Core becomes essential for components needing to adapt their behavior based on environment or deployment specifics. This article delves into different methods to achieve this, providing practical examples and best practices to ensure your application settings are readily available wherever needed.

Understanding the ASP.NET Core Configuration System

The configuration system in ASP.NET Core is built around the IConfiguration interface. This interface represents a set of key-value application configuration properties. The default configuration provider reads data from appsettings.json and appsettings.{Environment}.json files, as well as environment variables. This allows for environment-specific settings, ensuring your application behaves differently in development, staging, and production environments. The configuration system is designed to be extensible, allowing you to add custom configuration providers if needed, such as reading configuration from a database or a remote source. For example, you can easily add Azure Key Vault as a configuration provider to securely manage secrets. According to Microsoft’s documentation [Microsoft Configuration Docs], the configuration sources are read in a specific order, with later sources overriding earlier ones, giving precedence to environment variables and command-line arguments.

The IConfiguration interface provides methods to access configuration values by key. You can retrieve simple values like strings or integers, or access entire sections of the configuration as objects. This makes it easy to structure your configuration data in a way that reflects your application’s architecture. For instance, you might have a section dedicated to database settings, another for logging configuration, and so on. The configuration system also supports strongly-typed configuration, allowing you to map configuration sections to C classes. This approach provides type safety and improves code readability. For example, you might define a class called DatabaseSettings with properties like ConnectionString and Timeout, and then bind a corresponding section in your appsettings.json file to this class.

One of the key benefits of using the IConfiguration interface is its ability to abstract away the underlying configuration source. Your application code doesn’t need to know whether the configuration is coming from a JSON file, an environment variable, or a database. It simply retrieves the configuration value by key. This makes your code more portable and easier to test. You can easily swap out different configuration sources in different environments without modifying your application code. According to a Stack Overflow survey, approximately 70% of ASP.NET Core developers use the built-in configuration providers [Stack Overflow Developer Survey 2022], highlighting the widespread adoption of this system.

Dependency Injection (DI) for Configuration Access

The recommended way to access configuration in ASP.NET Core is through Dependency Injection (DI). DI is a design pattern that allows you to inject dependencies into your classes instead of creating them directly. This promotes loose coupling and makes your code more testable. In ASP.NET Core, the DI container is built into the framework and provides a central place to register and resolve dependencies. To access configuration using DI, you simply inject the IConfiguration interface into the constructor of your class. The DI container will then provide an instance of the IConfiguration interface that is configured with your application’s settings. This approach ensures that your class has access to the configuration without being tightly coupled to a specific configuration source.

Here’s a step-by-step guide to using DI for configuration access:

  1. Register the IConfiguration service in your Startup.cs or Program.cs file (this is typically done automatically by the framework).
  2. Inject the IConfiguration interface into the constructor of your class.
  3. Use the IConfiguration interface to access configuration values by key.

For example:

public class MyService { private readonly IConfiguration _configuration; public MyService(IConfiguration configuration) { _configuration = configuration; } public string GetSetting() { return _configuration["MySetting"]; } } 

This approach is clean, testable, and promotes good software design principles. Furthermore, you can bind specific configuration sections to strongly-typed classes and inject those directly. This is achieved using the IOptions interface, which provides a strongly-typed way to access configuration settings. For example, you could bind the “Database” section of your configuration to a DatabaseOptions class and then inject IOptions into your service.

Using IOptions for Strongly-Typed Configuration

While accessing configuration values directly through IConfiguration is straightforward, using IOptions offers several advantages, particularly for complex configurations. IOptions allows you to bind a specific section of your configuration to a strongly-typed class. This provides compile-time checking, improves code readability, and simplifies the process of accessing configuration values. The T in IOptions represents the class that will hold your configuration settings. This class should have properties that match the keys in your configuration section. This is particularly useful for organizing and managing complex configuration structures. The IOptions pattern promotes separation of concerns by encapsulating configuration access within a specific class, making it easier to maintain and test.

Here’s how to use IOptions:

  • Create a class to represent your configuration section (e.g., AppSettings).
  • Define properties in the class that match the keys in your configuration section.
  • Register the class with the DI container using services.Configure(Configuration.GetSection(“AppSettings”)).
  • Inject IOptions into your class.
  • Access the configuration values through the Value property of the IOptions interface.

Example:

public class AppSettings { public string Setting1 { get; set; } public int Setting2 { get; set; } } // In Startup.cs or Program.cs: services.Configure<appsettings>(Configuration.GetSection("AppSettings")); public class MyService { private readonly AppSettings _appSettings; public MyService(IOptions<appsettings> appSettings) { _appSettings = appSettings.Value; } public string GetSetting1() { return _appSettings.Setting1; } } </appsettings></appsettings>

Using IOptions promotes better code organization and type safety, reducing the risk of runtime errors due to misconfigured settings. It also allows for easier unit testing, as you can easily mock the IOptions interface and provide test-specific configuration values. This approach is especially beneficial when dealing with complex configuration structures that involve multiple nested sections and properties. This method is outlined in depth by Mads Kristensen in his blog post about strongly typed configuration [Mads Kristensen - Strongly Typed Configuration].

While Dependency Injection is the preferred method for accessing configuration, it is technically possible to access the IConfiguration directly using HttpContext.RequestServices or ConfigurationBuilder. However, this approach is generally discouraged because it tightly couples your code to the ASP.NET Core framework, making it harder to test and maintain. Direct access bypasses the DI container, making it difficult to mock or replace the configuration in unit tests. It also violates the principle of loose coupling, which is a fundamental tenet of good software design. While seemingly convenient, this approach can lead to brittle and inflexible code. It can also make your code harder to understand and debug, as the dependencies are not explicitly declared.

Featured Snippet: Directly accessing the IConfiguration instance using HttpContext.RequestServices is generally not recommended due to tight coupling and testability issues. The preferred method involves injecting IConfiguration or IOptions through dependency injection, promoting loose coupling and easier unit testing. While direct access might seem simpler for quick access, it can create significant maintenance headaches in the long run, especially as the application grows in complexity.

Even though direct access is discouraged, here’s an example of how it might be done (again, for demonstration purposes only):

// Warning: This is not the recommended approach! var configuration = context.HttpContext.RequestServices.GetService<iconfiguration>(); var mySetting = configuration["MySetting"]; </iconfiguration>

Using direct access can also make it harder to reason about the flow of your application. When dependencies are injected through the constructor, it is clear which components rely on which services. This makes it easier to understand the relationships between different parts of your application. In contrast, direct access can hide dependencies, making it harder to understand how different components interact. Furthermore, relying on HttpContext outside of controllers is often a sign of a design flaw. Consider refactoring your code to use dependency injection instead. Remember, embracing dependency injection leads to more maintainable, testable, and scalable applications.

Infographic here
FAQ ---
What is the difference between IConfiguration and IOptions?
IConfiguration provides direct access to configuration values by key, while IOptions allows you to bind a specific section of your configuration to a strongly-typed class.
Why is Dependency Injection recommended for accessing configuration?
Dependency Injection promotes loose coupling, improves testability, and makes your code more maintainable.
Can I use custom configuration providers?
Yes, ASP.NET Core allows you to add custom configuration providers, such as reading configuration from a database or a remote source.
What is the order of precedence for configuration sources?
Configuration sources are read in a specific order, with later sources overriding earlier ones, giving precedence to environment variables and command-line arguments.
- Use Dependency Injection for accessing configuration. - Prefer IOptions for strongly-typed configuration.
  • Avoid direct access to IConfiguration using HttpContext.RequestServices.
  • Register the IConfiguration service in your Startup.cs or Program.cs file.

Understanding how to effectively manage and access configuration in ASP.NET Core is a cornerstone of building robust, adaptable applications. By leveraging Dependency Injection and the IOptions pattern, you can create code that is easier to test, maintain, and scale. While direct access to configuration might seem tempting in certain scenarios, the long-term benefits of embracing Dependency Injection far outweigh any perceived short-term gains. By following these best practices, you can ensure that your application’s configuration is readily available wherever it’s needed, promoting a more organized and maintainable codebase.

Now that you understand the different methods for accessing configuration, consider exploring related topics such as environment-specific configuration and custom configuration providers. Dive deeper into the Microsoft documentation [Microsoft Docs - Configuration] and experiment with different configuration scenarios to solidify your understanding. This will empower you to build more resilient and flexible applications that can adapt to changing environments and requirements.

Question & Answer :
I have gone through configuration documentation on ASP.NET core. Documentation says you can access configuration from anywhere in the application.

Below is Startup.cs created by template

public class Startup { 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); if (env.IsEnvironment("Development")) { // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. builder.AddApplicationInsightsSettings(developerMode: true); } builder.AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseApplicationInsightsRequestTelemetry(); app.UseApplicationInsightsExceptionTelemetry(); app.UseMvc(); } } 

So in Startup.cs we configure all the settings, Startup.cs also has a property named Configuration

What I’m not able to understand how do you access this configuration in controller or anywhere in the application? MS is recommending to use options pattern but I have only 4-5 key-value pairs so I would like not to use options pattern. I just wanted to have access to Configuration in application. How do I inject it in any class?

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 } }