Multiple Elasticsearch connection in singleton object Getting one specific Singleton elastic search in controller class

女生的网名这么多〃 提交于 2021-02-05 08:16:45

问题


Passing AcqClient and NcClient to the same interface

//AcqClient and NcClient are static ReadOnly Variables

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

Creating Singleton Object

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

Implementing in Startup.cs

  service.Connection(configuration)

On my controller class when i am doing this i am getting the last one object

    public class controller:Controller{
     public controller(IElasticClient elasticclient){
     
        _elasticclient=elasticlient;
        }
     }

回答1:


I have done it like this

IServiceCollection Delegate

public delegate IServiceCollection ServiceResolver(string key);

Creating Elastic Search Singleton Object

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

Creating Object using ServiceResolver


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

In One Controller Different Node Connection Of 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>();
        }

In Other Controller

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


来源:https://stackoverflow.com/questions/63949465/multiple-elasticsearch-connection-in-singleton-object-getting-one-specific-singl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!