![.netcore](https://img.tnblog.net/arcimg/hb/c857299a86d84ee7b26d181a31e58234.jpg ".netcore")
>#.net core 选项框架:服务组件集成配置的最佳实践
[TOC]
#### 如何通过选项框架来处理服务和配置的关系?
特性
------------
- 支持单例模式读取配置
- 支持快照
- 支持配置变更通知
- 支持运动时动态修改选项值
设计原则
------------
- 接口分离原则(ISP),我们的类不应该依赖它不使用的配置
- 关注点分离(SoC),不同组件、服务、类之间的配置不应相互依赖或耦合
建议
------------
- 为我们的服务设计 XXXOptions
- 使用 IOptions、IOptionsSnapshort、IOptionsMonitor作为服务构造函数的参数
项目结构
------------
>这里我们创建的是一个WebAPI
![项目结构](https://img.tnblog.net/arcimg/hb/aad5ba56663142d0b8b771c09a102e2d.png)
通过选项注入案例
------------
>###项目内容
>OrderService.cs
```csharp
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
```csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton();
services.AddSingleton();
services.AddControllers();
}
```
>WeatherForecastController.cs
```csharp
[HttpGet]
public int Get([FromServices]IOrderService orderService)
{
Console.WriteLine($"orderService.ShowMaxOrderCount:{orderService.ShowMaxOrderCount()}");
return orderService.ShowMaxOrderCount();
}
```
>运行结果
![运行结果](https://img.tnblog.net/arcimg/hb/ae3b3e58b6f34da9ad34a5f23885834a.png)
服务组件集成配置
------------
>###修改项目内容
>OrderServiceExtensions.cs
```csharp
namespace Microsoft.Extensions.DependencyInjection
{
public static class OrderServiceExtensions
{
public static IServiceCollection AddOrderService(this IServiceCollection services,Action action)
{
return services;
}
}
}
```
>OrderService.cs
```csharp
public class OrderService : IOrderService
{
IOptions _orderServiceOptions;
public OrderService(IOptions orderServiceOptions)
{
_orderServiceOptions = orderServiceOptions;
}
public int ShowMaxOrderCount()
{
return _orderServiceOptions.Value.MaxOrderCount;
}
}
```
>Startup.cs
```csharp
public void ConfigureServices(IServiceCollection services)
{
services.Configure(Configuration.GetSection("OrderService"));
services.AddSingleton();
services.AddControllers();
}
```
>appsetting.json
```json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"OrderService": {
"MaxOrderCount": 200
},
"AllowedHosts": "*"
}
```
>运行结果
![运行结果](https://img.tnblog.net/arcimg/hb/fdbcf7acb3834b039268dedf5e32cf07.png)
>我们可以看见这里的值通过配置而发生了变化
其他
------------
>内置的配置优先级高到低是:
命令行配置
环境变量配置
文件配置