ASP.NET vNext global config access

后端 未结 2 779
清酒与你
清酒与你 2021-01-22 20:40

What is the correct/recommended way of accessing the config.json file (or wherever else config is stored) in ASP.NET vNext?

In the Startup clas

2条回答
  •  一生所求
    2021-01-22 20:59

    In the first place, you should avoid registering your database context as a singleton. Also passing around the raw IConfiguration interface isn't a good practice.

    In stead could create a POCO options class:

    public class DbOptions
    {
        public string ConnectionString { get; set }
    }
    

    And populate it in the ConfigureServices method using the section in the config.json:

    services.Configure(Configuration.GetConfigurationSection("Data:DefaultConnection"));
    

    Then you can inject it into your DbContext (and in controllers, etc.):

    public sealed class Context : IdentityDbContext
    {
        private readonly DbOptions _options;
    
        public DbSet Clients { get; set; }
    
        public Context(IOptions optionsAccessor)
        {
            // store the injected options
            _options = optionsAccessor.Options;
        }
    
        // other code..
    }
    

提交回复
热议问题