asp.net core 2.1 配置管理

1. 直接读取配置

StartUp类中使用 Configuration["ConnectionString"], Configuration["AliyunAkSk:Ak"]

如果在Service中想读取配置, 就先注入IConfiguration configuration

 

2. 配置强类型化读取

现有配置节点如下

"OssSettings": {
     "ConfigItems": [
       {
         "Name": "ali_",
         "Domain": "img.",
         "OfficalDomain": "img.",
         "AccessId": "",
         "AccessKey": "",
         "EndPoint": "
http://",
         "BucketName": "",
         "Platform": "ali"
       }
     ],
     "CurrentOssName": "al",
     "TemplateOssName": ""
   }

定义一个接口, 并实现这个接口.

public interface IOssSettings
    {
         IEnumerable<OssConfig> ConfigItems { get;  }
         string CurrentOssName { get;  }
         string TemplateOssName { get; }
    }

然后在StartUp的ConfigureServices中添加注入

services.AddSingleton<IOssSettings>((os) =>
             {
                 var section = Configuration.GetSection("OssSettings");
                 return section.Get<OssSettings>();
             });

之后就可以在任何地方愉快滴使用 IOssSettings来注入使用了

 

3. 外置配置文件

public class Program
    {
        public static void Main(string[] args)
        { 

            CreateWebHostBuilder(args).Build().Run();
        }

        private static IConfiguration configuration {
            get
            {
                var configuration = 
                    new ConfigurationBuilder()
                                        .SetBasePath(Directory.GetCurrentDirectory())
                                        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)

                                        // custom config file
                                        .AddJsonFile("GlobalSettings.json", optional: false, reloadOnChange: false)
                                        .Build();
                return configuration;
            }
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args) 
            .UseConfiguration(configuration)
                .UseStartup<Startup>(); 
    }

新建一个类GlobalSettings
services.Configure<GlobalSettings>(Configuration);

 需要使用Options注入使用, 见 https://www.cnblogs.com/qinzb/p/9297143.html

然后就可以使用上面介绍的方式来注入使用了

posted @ 2018-08-27 15:20  MyCoolDog  阅读(803)  评论(0编辑  收藏  举报