【发布时间】:2019-08-04 15:11:49
【问题描述】:
如何在 .NET Core 应用程序中将 ElasticClient 注册为单例,但仍能在查询期间指定不同的索引?
例如:
在 Startup.cs 中,我将弹性客户端对象注册为单例,仅提及 URL 而不指定索引。
public void ConfigureServices(IServiceCollection services)
{
....
var connectionSettings = new ConnectionSettings(new Uri("http://localhost:9200"));
var client = new ElasticClient(connectionSettings);
services.AddSingleton<IElasticClient>(client);
....
}
然后在上面注入 ElasticClient 单例对象时,我想将它用于 2 个不同查询中的不同索引。
在下面的类中,我想从一个名为“Apple”的索引中查询
public class GetAppleHandler
{
private readonly IElasticClient _elasticClient;
public GetAppleHandler(IElasticClient elasticClient)
{
_elasticClient = elasticClient;
}
public async Task<GetAppleResponse> Handle()
{
// I want to query (_elasticClient.SearchAsync<>) using an index called "Apple" here
}
}
从下面的代码中我想从一个名为“Orange”的索引中查询
public class GetOrangeHandler
{
private readonly IElasticClient _elasticClient;
public GetOrangeHandler(IElasticClient elasticClient)
{
_elasticClient = elasticClient;
}
public async Task<GetOrangeResponse> Handle()
{
// I want to query (_elasticClient.SearchAsync<>) using an index called "Orange" here
}
}
我该怎么做?如果不可能,您能否建议其他方法允许我通过 .NET Core 依赖注入注入 ElasticClient,同时还允许我从同一个 ES 实例的 2 个不同索引进行查询?
【问题讨论】:
标签: elasticsearch asp.net-core dependency-injection .net-core nest