首先引用NuGet包
- Microsoft.Extensions.Configuration
- Microsoft.Extensions.Configuration.Json
- Microsoft.Extensions.DependencyInjection
- Microsoft.Extensions.Options
- Microsoft.Extensions.Options.ConfigurationExtensions
我们先来看一下appsettings.json文件
- {
- "Logging": {
- "IncludeScopes": false,
- "Debug": {
- "LogLevel": {
- "Default": "Warning"
- }
- },
- "Console": {
- "LogLevel": {
- "Default": "Warning"
- }
- }
- },
- "AppSupportDatabase": {
- "ConnectionString": "server=.;initial catalog=TestDB;user id=sa;password=123",
- "ProviderName": "System.Data.SqlClient"
- }
- }
我们想取ProviderName怎么办呢?首先新建ConfigManager
- public class ConfigManager
- {
- public string ProviderName { get; set; }
- public string ConnectionString { get; set; }
- }
GetAppsettings方法
- public T GetAppsettings<T>(string key) where T : class, new()
- {
- string keyDir = System.IO.Directory.GetCurrentDirectory();
- IConfiguration config = new ConfigurationBuilder()
- .SetBasePath(keyDir)
- .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
- .Build();
- var appconfig = new ServiceCollection()
- .AddOptions()
- .Configure<T>(config.GetSection(key))
- .BuildServiceProvider()
- .GetService<IOptions<T>>()
- .Value;
- return appconfig;
- }
调用例子
- GetAppsettings<ConfigManager>("AppSupportDatabase").ProviderName