Search code examples
c#asp.net-coreasp.net-core-mvc

How do I access Configuration in any class in ASP.NET Core?


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?


Solution

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