Using IConfiguration globally in mvc6

前端 未结 1 504
盖世英雄少女心
盖世英雄少女心 2020-12-06 11:25

I have Probably been staring at this for to long, but I have jumped into MVC6 for asp.net for the last few days, while I am really enjoying this, I can\'t seem to find a con

相关标签:
1条回答
  • 2020-12-06 11:44

    Only do the loading of Configurations in your Startup.cs. If you need them elsewhere later you could load the values into appropriate POCOs and register them in the DI so you can inject them where you need them. This allows you to organize your configuration in different files, and in different POCOs in a way that makes sense to your application. There is already built in support for this in the dependency injection. Here is how you would do it:

    A POCO to put your configuration in:

    public class SomeOptions
    {
        public string EndpointUrl { get; set; }
    }
    

    Your Startup.cs loads the configuration into the POCO and registers it in the DI.

    public class Startup
    {
        public Startup()
        {
            Configuration = new Configuration()
                        .AddJsonFile("Config.json")
                        .AddEnvironmentVariables();
        }
    
        public IConfiguration Configuration { get; set; }
    
        public void Configure(IApplicationBuilder app)
        {
            app.UseMvc();
        }
    
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<SomeOptions>(options => 
                options.EndpointUrl = Configuration.Get("EndpointUrl"));
    
            services.AddMvc();
        }
    }
    

    Then in your controller get the configuration POCO you created in the Startup.cs through dependency injection like this:

    public class SomeController
    {
        private string _endpointUrl;
        public SomeController(IOptions<SomeOptions> options)
        {
            _endpointUrl = options.Options.EndpointUrl;
        }
    }
    

    Tested with 1.0.0-beta1 builds of aspnet5.

    For more information see The fundamentals of ASP.Net 5 Configuration.

    0 讨论(0)
提交回复
热议问题