繁体   English   中英

依赖注入和连接字符串/singleton 的多个实例

[英]Dependency Injection & connection strings / Multiple instances of a singleton

我有一个 Web Api 项目,它严重依赖于 Azure Cosmos DB。 到目前为止,拥有一个 Cosmos DB 帐户(一个连接字符串)就足够了。 现在一个新的要求是能够根据传入的参数连接到不同的 Cosmos(两个连接字符串)。

对于 customerId X,我们应该从 Cosmos DB 1 获取文档,对于另一个客户 Y,我们必须在 Cosmos DB 2 中查找。

到目前为止,我的 Startup.cs 文件注册了 CosmosClient 的 singleton 实例。 反过来像这样实例化 cosmosClient = new CosmosClient(endpointUrl, primaryKey); 这非常有效。 Web Api 能够轻松处理所有请求。 但是现在我们必须为每个请求新建一个 CosmosClient,性能真的很差。

所以我的问题是; 有没有办法拥有相同 singleton 的多个实例? 如; 我们可以创建 Class+EndPointUrl 组合的单个实例吗? (那仍然是 singleton 吗?)

现在,我们每分钟都在更新数千个 CosmosClients。 与我们之前的相比,我们真的只需要一个。

有多种方法可以做到这一点,但一个简单的实现是围绕您使用的每个CosmosClient创建一个包装器。 包装器的唯一用途是允许您使用CosmosClient的各种实例并通过它们的类型来区分它们。

//Create your own class for each client inheriting the behaviour of CosmosClient
public class ContosoCosmosClient : CosmosClient
{
    public ContosoCosmosClient(string connectionString, CosmosClientOptions clientOptions = null) : base(connectionString, clientOptions)
    {
    }

    public ContosoCosmosClient(string accountEndpoint, string authKeyOrResourceToken, CosmosClientOptions clientOptions = null) : base(accountEndpoint, authKeyOrResourceToken, clientOptions)
    {
    }

    public ContosoCosmosClient(string accountEndpoint, TokenCredential tokenCredential, CosmosClientOptions clientOptions = null) : base(accountEndpoint, tokenCredential, clientOptions)
    {
    }
}
//In Startup.up add a Singleton for each client
services.AddSingleton(new ContosoCosmosClient(...));
services.AddSingleton(new FabrikamCosmosClient(...));

然后在您的业务逻辑中,您可以添加两个客户端,并根据您的逻辑选择要使用的客户端:

public class MyService
{
    public MyService(ContosoCosmosClient contosoClient, FabrikamCosmosClient fabrikamClient)
    {
        //...
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM