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
然後就可以使用上面介紹的方式來注入使用了