15 | 选项框架:服务组件集成配置的最佳实践
特性
- 支持单例模式读取配置
- 支持快照
- 支持配置变更通知
- 支持运行时动态修改选项值
设计原则
- 接口分离原则(LSP),我们的类不应该依赖它不适用的配置
- 关注点分离(SOC),不同组件、服务、类之间的配置不应相互依赖或耦合
建议
- 为我们的服务设计
XXXOptions
- 使用
IOptions<XXXOptions>
、IOptionsSnapshot<XXXOptions>
、IOptionsMonitor<XXXOptions>
作为服务构造函数的参数
示例
新建Web应用程序👉命名OptionsDemo
👉模板选择API
👉新建Services
文件夹👉新建OrderService
类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OptionsDemo.Services
{
public interface IOrderService { int ShowMaxOrderCount(); }
public class OrderService : IOrderService
{
private readonly OrderServiceOptions _options;
public OrderService(OrderServiceOptions options)
{
_options = options;
}
public int ShowMaxOrderCount()
{
return _options.MaxOrderCount;
}
}
public class OrderServiceOptions
{
public int MaxOrderCount { get; set; } = 200;
}
}
将其注册
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<OrderServiceOptions>();
services.AddSingleton<IOrderService, OrderService>();
services.AddControllers();
}
将Controller
文件中WeatherForecastController
类Get
方法修改为
[HttpGet]
public int Get([FromServices]IOrderService orderService)
{
return orderService.ShowMaxOrderCount();
}
执行输出:
这个200
是从OrderServiceOptions
类MaxOrderCount
属性中获取的,如果说我们需要把这个值跟配置像绑定,怎么去做呢
首先我们需要引入Options
框架,实际上AspNetCore已经默认的帮我们把框架引入进来了,命名空间是在Microsoft.Extensions.Options
我们需要修改以下我们的服务入参,将OrderServiceOptions
修改为IOptions<OrderServiceOptions>
,通过Value
获取MaxOrderCount
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
namespace OptionsDemo.Services
{
public interface IOrderService { int ShowMaxOrderCount(); }
public class OrderService : IOrderService
{
private readonly IOptions<OrderServiceOptions> _options;
public OrderService(IOptions<OrderServiceOptions> options)
{
_options = options;
}
public int ShowMaxOrderCount()
{
return _options.Value.MaxOrderCount;
}
}
public class OrderServiceOptions
{
public int MaxOrderCount { get; set; } = 200;
}
}
那么注册的时候,不再是把我们的Options
类型注册进去,而是用Configure
方法。
我们这里需要从配置文件里去读取,将appsetting.json
添加一节叫OrderService
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"OrderService": {
"MaxOrderCount": 10086
}
}
将这一节取出来,并配置给它
public void ConfigureServices(IServiceCollection services)
{
services.Configure<OrderServiceOptions>(Configuration.GetSection("OrderService"));
services.AddSingleton<IOrderService, OrderService>();
services.AddControllers();
}
运行输出:
本文作者:hiwwwk
本文链接:https://www.cnblogs.com/wwwk/p/15873381.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步