.NetCore【基础】配置注入
appsetting
Ioc注入到controller中
- 定义model和config
namespace Demo.gRPCaggregate.Client.Discovery.Model
{
public class ServiceDiscoveryOptions
{
public string ServiceName { get; set; }
public string ServiceIP { get; set; }
public int ServicePort { get; set; }
public string ServiceHealthCheck { get; set; }
public string ConsulAddress { get; set; }
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConsulSetting": {
"ServiceName": "OrderService",
"ServiceIP": "localhost",
"ServicePort": 49725,
"ServiceHealthCheck": "/HealthCheck",
"ConsulAddress": "http://localhost:8500/" //Consul地址
}
}
- 注册config
// 注册config
services.Configure<ServiceDiscoveryOptions>(Configuration.GetSection("ConsulSetting"));
- controller中调用
[Route("api/[controller]")]
[ApiController]
public class AggregateController : ControllerBase
{
private readonly ServiceDiscoveryOptions ServiceDiscoveryOptions;
public AggregateController(
IOptions<ServiceDiscoveryOptions> options)
{
this.ServiceDiscoveryOptions = options.Value;
}
}