
.net core 选项框架:服务组件集成配置的最佳实践
如何通过选项框架来处理服务和配置的关系?
特性
- 支持单例模式读取配置
- 支持快照
- 支持配置变更通知
- 支持运动时动态修改选项值
设计原则
- 接口分离原则(ISP),我们的类不应该依赖它不使用的配置
- 关注点分离(SoC),不同组件、服务、类之间的配置不应相互依赖或耦合
建议
- 为我们的服务设计 XXXOptions
- 使用 IOptions
、IOptionsSnapshort 、IOptionsMonitor 作为服务构造函数的参数
项目结构
这里我们创建的是一个WebAPI
通过选项注入案例
项目内容
OrderService.cs
public interface IOrderService
{
int ShowMaxOrderCount();
}
public class OrderService : IOrderService
{
OrderServiceOptions _orderServiceOptions;
public OrderService(OrderServiceOptions orderServiceOptions)
{
_orderServiceOptions = orderServiceOptions;
}
public int ShowMaxOrderCount()
{
return _orderServiceOptions.MaxOrderCount;
}
}
public class OrderServiceOptions
{
public int MaxOrderCount { get; set; } = 100;
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<OrderServiceOptions>();
services.AddSingleton<IOrderService, OrderService>();
services.AddControllers();
}
WeatherForecastController.cs
[HttpGet]
public int Get([FromServices]IOrderService orderService)
{
Console.WriteLine($"orderService.ShowMaxOrderCount:{orderService.ShowMaxOrderCount()}");
return orderService.ShowMaxOrderCount();
}
运行结果
服务组件集成配置
修改项目内容
OrderServiceExtensions.cs
namespace Microsoft.Extensions.DependencyInjection
{
public static class OrderServiceExtensions
{
public static IServiceCollection AddOrderService(this IServiceCollection services,Action<OrderServiceOptions> action)
{
return services;
}
}
}
OrderService.cs
public class OrderService : IOrderService
{
IOptions<OrderServiceOptions> _orderServiceOptions;
public OrderService(IOptions<OrderServiceOptions> orderServiceOptions)
{
_orderServiceOptions = orderServiceOptions;
}
public int ShowMaxOrderCount()
{
return _orderServiceOptions.Value.MaxOrderCount;
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.Configure<OrderServiceOptions>(Configuration.GetSection("OrderService"));
services.AddSingleton<IOrderService, OrderService>();
services.AddControllers();
}
appsetting.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"OrderService": {
"MaxOrderCount": 200
},
"AllowedHosts": "*"
}
运行结果
我们可以看见这里的值通过配置而发生了变化
其他
内置的配置优先级高到低是:
命令行配置
环境变量配置
文件配置
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739
评价
排名
2
文章
634
粉丝
44
评论
93
docker中Sware集群与service
尘叶心繁 : 想学呀!我教你呀
一个bug让程序员走上法庭 索赔金额达400亿日元
叼着奶瓶逛酒吧 : 所以说做程序员也要懂点法律知识
.net core 塑形资源
剑轩 : 收藏收藏
映射AutoMapper
剑轩 :
好是好,这个对效率影响大不大哇,效率高不高
一个bug让程序员走上法庭 索赔金额达400亿日元
剑轩 : 有点可怕
ASP.NET Core 服务注册生命周期
剑轩 :
http://www.tnblog.net/aojiancc2/article/details/167
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256


欢迎加群交流技术
bk
我选择 Ctrl + R![[嘻嘻]](https://www.tnblog.net/layui/images/face/1.gif)