多个elasticsearch连接在controller类中获得一个特定的singletonElasticSearch

ctzwtxfj  于 2021-06-14  发布在  ElasticSearch
关注(0)|答案(1)|浏览(327)

将acqclient和ncclient传递到同一接口
//acqclient和ncclient是静态只读变量

public static void Connection(){
        AcqClient = new ElasticClient(AcqConnection);
        NcClient= new ElasticClient(NcConnection);

创建单例对象

services.AddSingleton<IElasticClient>(AcqClient);
        services.AddSingleton<IElasticClient>(NcClient);
     }

在startup.cs中实现

service.Connection(configuration)

在我的控制器类上,当我这样做时,我得到的是最后一个对象

public class controller:Controller{
     public controller(IElasticClient elasticclient){

        _elasticclient=elasticlient;
        }
     }
y0u0uwnf

y0u0uwnf1#

我是这样做的
iservicecollection委托 public delegate IServiceCollection ServiceResolver(string key); 创建ElasticSearch单例对象

var firstobject = new ElasticClient(firstconnection);
   var secondobject= new ElasticClient(secondconnection);

使用serviceresolver创建对象

services.AddTransient<ServiceResolver>(serviceProvider => key =>
             {
                if (key== "A")
                {
                   services.AddSingleton<IElasticClient>(firstobject);
                }
                else if (key == "N")
                {
                    services.AddSingleton<IElasticClient>(secondobject);
                }
                return services;
        });

在一个控制器中,ElasticSearch的不同节点连接

private static IElasticClient _elasticClient;
        private readonly IServiceCollection _aService;

        public static string clsName = "ElasticRandDController";

        public FirstConstructor(ServiceResolver serviceAccessor)
        {

            _aService = serviceAccessor("N");
             var serviceProvider = _aService.BuildServiceProvider();
            _elasticClient = serviceProvider.GetService<IElasticClient>();
        }

在其他控制器中

private static IElasticClient _elasticClient;
        private readonly IServiceCollection _aService;
        public SecondConstructor(ServiceResolver serviceAccessor)
        {
            _aService = serviceAccessor("A");
            var serviceProvider = _aService.BuildServiceProvider();
            _elasticClient = serviceProvider.GetService<IElasticClient>();
        }

相关问题