namespace OptionsDemo.Services
{
public interface IOrderService
{
int ShowMaxOrderCount();
}
public class OrderService : IOrderService
{
OrderServiceOptions _options;
public OrderService(OrderServiceOptions options)
{
_options = options;
}
public int ShowMaxOrderCount()
{
return _options.MaxOrderCount;
}
}
// 代表从配置中读取的值
public class OrderServiceOptions
{
public int MaxOrderCount { get; set; } = 100;
}
}
接着是服务注册
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<OrderServiceOptions>();
services.AddSingleton<IOrderService, OrderService>();
}
接着是控制器的定义
[HttpGet]
public int Get([FromServices]IOrderService orderService)
{
Console.WriteLine($"orderService.ShowMaxOrderCount:{orderService.ShowMaxOrderCount()}");
return 1;
}
注释默认方法
//[HttpGet]
//public IEnumerable<WeatherForecast> Get()
//{
// var rng = new Random();
// return Enumerable.Range(1, 5).Select(index => new WeatherForecast
// {
// Date = DateTime.Now.AddDays(index),
// TemperatureC = rng.Next(-20, 55),
// Summary = Summaries[rng.Next(Summaries.Length)]
// })
// .ToArray();
//}
启动程序,输出如下:
orderService.ShowMaxOrderCount:100
如果说我们需要把这个值跟配置绑定,怎么做呢?
首先需要引入 Options 框架
ASP.NET Core 实际上已经默认帮我们把框架引入进来了
命名空间是:Microsoft.Extensions.Options
我们需要修改一下服务的入参
public class OrderService : IOrderService
{
//OrderServiceOptions _options;
IOptions<OrderServiceOptions> _options;
//public OrderService(OrderServiceOptions options)
public OrderService(IOptions<OrderServiceOptions> options)
{
_options = options;
}
public int ShowMaxOrderCount()
{
//return _options.MaxOrderCount;
return _options.Value.MaxOrderCount;
}
}
注册的时候使用 config 方法,从配置文件读取
public void ConfigureServices(IServiceCollection services)
{
//services.AddSingleton<OrderServiceOptions>();
services.Configure<OrderServiceOptions>(Configuration.GetSection("OrderService"));
services.AddSingleton<IOrderService, OrderService>();
}