NetCore6.0 选项模式

读取相关配置值的首选方法是使用选项模式。 选项模式可以通过 IOptions<TOptions> 接口实现,其中泛型类型参数 TOptions 被约束为 class。 以后可以通过依赖关系注入来提供 IOptions<TOptions>

1、编写绑定配置文件的类方法

 1     public static class LaunchConfigHelper
 2     {
 3         /// <summary>
 4         /// 获取配置文件
 5         /// </summary>
 6         /// <param name="file">配置文件AppConfig.json</param>
 7         /// <returns></returns>
 8         public static IConfigurationRoot GetJsonConfig(string file)
 9         {
10             return new ConfigurationBuilder()
11                 .AddInMemoryCollection()
12                 .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "Config"))//配置文件所在路径
13                 .AddJsonFile(file)
14                 .Build();
15         }
16     }

注意:安装Microsoft.Extensions.Configuration.Json 引用 ,否则 SetBasePath 节点会报错

2、在Program.cs启动程序中调用

1 var conf = LaunchConfigHelper.GetJsonConfig("AppConfig.json");//调用绑定配置文件方法
2 builder.Services.Configure<Dictionary<string, string>>(conf.GetSection("BasicConfigs"));// 加载配置文件BasicConfigs节点到TOptions
3
builder.Services.Configure<List<Student>>(conf.GetSection("StudentConfigs"));//挂载设备通信信息,也可用实体类等其他类型接收配置信息

3、利用依赖注入进行取值

 1     [ApiController]
 2     [Route("[controller]")]
 3     public class XmlController : Controller
 4     {
 5         protected Dictionary<string, string> _options;
 6         public XmlController(IOptions<Dictionary<string, string>> options)
 7         {
 8             _options = options.Value;
 9         }
10 
11     }

杨中科老师教学中的读取配置方式供参考

1、从配置中读取相关信息

1            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
2             configurationBuilder.AddJsonFile("config.json", optional: false, reloadOnChange: false);
3             IConfigurationRoot config = configurationBuilder.Build();
4             var sendSocketLink = config.GetSection("Socket:SendSocketLink").Value;
5             Console.WriteLine($"socket地址:{sendSocketLink}");
6             return sendSocketLink;

2、配置文件

 1 {
 2   "compilerOptions": {
 3     "noImplicitAny": false,
 4     "noEmitOnError": true,
 5     "removeComments": false,
 6     "sourceMap": true,
 7     "target": "es5"
 8   },
 9   "exclude": [
10     "node_modules",
11     "wwwroot"
12   ],
13   "socket": {
14     "sendSocketLink": "ws://192.168.4.192:8182"
15   }
16 }

 

微软官方说明:https://learn.microsoft.com/zh-cn/dotnet/core/extensions/options

参考博客地址:https://blog.csdn.net/sD7O95O/article/details/78096182

posted @ 2023-04-24 09:37  Fast & Furious  阅读(35)  评论(0)    收藏  举报