15 | 选项框架:服务组件集成配置的最佳实践
特性
- 支持单例模式读取配置
- 支持快照
- 支持配置变更通知
- 支持运行时动态修改选项值
设计原则
- 接口分离原则(LSP),我们的类不应该依赖它不适用的配置
- 关注点分离(SOC),不同组件、服务、类之间的配置不应相互依赖或耦合
建议
- 为我们的服务设计
XXXOptions
- 使用
IOptions
、IOptionsSnapshot
、IOptionsMonitor
作为服务构造函数的参数
示例
新建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();
services.AddSingleton();
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
,通过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 _options;
public OrderService(IOptions 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(Configuration.GetSection("OrderService"));
services.AddSingleton();
services.AddControllers();
}
运行输出: