.NetCore【基础】配置注入

appsetting

Ioc注入到controller中

  1. 定义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地址
  }
}


  1. 注册config

// 注册config
services.Configure<ServiceDiscoveryOptions>(Configuration.GetSection("ConsulSetting"));
  1. controller中调用
[Route("api/[controller]")]
[ApiController]
public class AggregateController : ControllerBase
{
    private readonly ServiceDiscoveryOptions ServiceDiscoveryOptions;
    public AggregateController(
       IOptions<ServiceDiscoveryOptions> options)
    {
        this.ServiceDiscoveryOptions = options.Value;
    }
}

posted on 2022-12-04 22:39  杏村牧童  阅读(164)  评论(0编辑  收藏  举报