Get Multiple Connection Strings in appsettings.json without EF

前端 未结 3 739
天命终不由人
天命终不由人 2021-01-12 08:08

Just starting playing with the .Net Core RC2 by migrating a current MVC .Net app I developed. It looks like to me because of the way that configuration is handled with apps

3条回答
  •  清酒与你
    2021-01-12 08:41

    You can use Options to access in DAL layer. I will try to write simple example(RC1):

    First you need to create appsettings.json file with below content:

    {
        "ConnectionStrings": {
          "DefaultConnectionString": "Default",
          "CustomConnectionString": "Custom"
        }
    }
    

    Then create a class:

    public class ConnectionStrings
    {
        public string DefaultConnectionString { get; set; }
    
        public string CustomConnectionString { get; set; }
    }
    

    And in Startup.cs

        private IConfiguration Configuration;
        public Startup(IApplicationEnvironment app)
        {
            var builder = new ConfigurationBuilder()
               .SetBasePath(app.ApplicationBasePath)
               .AddJsonFile("appsettings.json");
    
            Configuration = builder.Build();
        }
        public void ConfigureServices(IServiceCollection services)
        {
            // ....
            services.AddOptions();
            services.Configure(Configuration.GetSection("ConnectionStrings"));
        }
    

    Finally inject it in the DAL class:

        private IOptions _connectionStrings;
        public DalClass(IOptions connectionStrings)
        {
            _connectionStrings = connectionStrings;
        }
        //use it
    

提交回复
热议问题