一、关键类型
IOptionsMonitor<out TOptions> //服务注册services.AddSingleton时使用
IOptionsSnapshot<out TOptions> //服务注册services.AddScoped 时使用
二、IOptionsSnapshot 方式
1.接口定义
public interface IOrderService
{
int ShowMaxOrderCount();
}
2.接口实现
public class OrderService : IOrderService
{
IOptionsSnapshot<OrderServiceOptions> _options;
public OrderService(IOptionsSnapshot<OrderServiceOptions> options)
{
_options = options;
}
public int ShowMaxOrderCount()
{
return _options.Value.MaxOrderCount;
}
}
public class OrderServiceOptions
{
public int MaxOrderCount { get; set; } = 100;
}
3.服务注册
services.Configure<OrderServiceOptions>(Configuration.GetSection("OrderService")); //从配置文件中获取配置信息,也可以从其它方式获取配置信息
services.AddScoped<IOrderService, OrderService>();
三、IOptionsMonitor 方式
1.接口定义
public interface IOrderService
{
int ShowMaxOrderCount();
}
2.接口实现
public class OrderService : IOrderService
{
IOptionsMonitor<OrderServiceOptions> _options;
public OrderService(IOptionsMonitor<OrderServiceOptions> options)
{
_options = options;
//每次配置信息变更的回调
_options.OnChange(option =>
{
Console.WriteLine($"配置更新了,最新的值是:{_options.CurrentValue.MaxOrderCount}");
});
}
public int ShowMaxOrderCount()
{
return _options.CurrentValue.MaxOrderCount;
}
}
public class OrderServiceOptions
{
public int MaxOrderCount { get; set; } = 100;
}
3.服务注册
services.Configure<OrderServiceOptions>(Configuration.GetSection("OrderService")); //从配置文件中获取配置信息,也可以从其它方式获取配置信息
services.AddSingleton<IOrderService, OrderService>();
四、对以加载的配置信息后进行内存修改
services.PostConfigure<OrderServiceOptions>(options =>
{
options.MaxOrderCount += 20;
});