特性
- 支持单例模式读取配置
- 支持快照
- 支持配置变更通知
- 支持运行时动态修改选项值
设计原则
- 接口分离原则(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();}
运行输出:
