netcore中使用构造函数依赖注入读取配置文件
第一步:建立配置文件
.netcore的MVC项目在创建时会自动生成appsettings.json文件,如下:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "DB": { "SqlServerConnectionString": "SqlServer库连接", "MySqlConnectionString": "MySql库连接", "DmConnectionString": "达梦库连接", "DbType": "DM" } }
第二步:建立实体类
public class DbSettings { public string DbType { get; set; } public string SqlServerConnectionString { get; set; } public string DmConnectionString { get; set; } }
第三步:Programs.cs 文件的var app = builder.Build();的上方加入以下代码:
//清晰版 ConfigurationBuilder configBuilder = new ConfigurationBuilder(); configBuilder.AddJsonFile("appsettings.json"); IConfigurationRoot root = configBuilder.Build(); builder.Services.AddOptions() .Configure<DbSettings>(root.GetSection("DB").Bind);
下面的是上面语句的链式简化版,作用相同。
//简化版 builder.Services.AddOptions() .Configure<DbSettings> ( new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build() .GetSection("DB") .Bind );
第四步:Controller中注入
public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private readonly IOptionsSnapshot <DbSettings> _optConfig; public HomeController(ILogger<HomeController> logger, IOptionsSnapshot<DbSettings> optConfig) { _logger = logger; this._optConfig = optConfig; } public IActionResult Index() { string s = _optConfig.Value.SqlServerConnectionString; string dm = _optConfig.Value.DmConnectionString; string result = string.Concat(s," , " ,dm,""); return Content(result); }
}
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "DB": { "SqlServerConnectionString": "SqlServer库连接", "MySqlConnectionString": "MySql库连接", "DmConnectionString": "达梦库连接", "DbType": "DM" }}