问题
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