【问题标题】:Dependency injection in .NET Azure Functions - Azure Cosmos DB Client.NET Azure Functions 中的依赖注入 - Azure Cosmos DB 客户端
【发布时间】:2019-10-15 07:25:01
【问题描述】:

我在 Microsoft Docs 上阅读了一篇关于使用 dependency injection in .NET Azure Functions 的文章。

一切正常,正如您在文章中看到的那样,它注册了 CosmosClient

builder.Services.AddSingleton((s) => {
     return new CosmosClient(Environment.GetEnvironmentVariable("COSMOSDB_CONNECTIONSTRING"));
    });

问题是,如何在我的函数中使用 Cosmos Client? 我不想每次都创建 Cosmos Client 实例。

public  class CosmosDbFunction
{
    public CosmosDbFunction()
    {

    }

    [FunctionName("CosmosDbFunction")]
    public  async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        // TODO: do something later
        return null;
    }
}

【问题讨论】:

  • 通过构造函数或 Run 将其注入函数,就像使用 log 一样
  • 问题是没有ICosmosClient。
  • 然后创建您自己的服务抽象来包装实现并公开所需的功能。
  • 另外,如果 cosmos 客户端作为单例添加,那么它应该只创建一次

标签: azure dependency-injection azure-functions azure-cosmosdb


【解决方案1】:

你没有使用界面。你可以直接注入CosmosClient

There's an example of this in the Cosmos client samples directory 包含以下代码:

private CosmosClient cosmosClient;
public AzureFunctionsCosmosClient(CosmosClient cosmosClient)
{
    this.cosmosClient = cosmosClient;
}

对于测试,似乎创建此客户端的团队已决定将所有内容抽象/虚拟化以允许模拟框架根据需要覆盖方法。这在issue #303 中有所提及。另请参阅堆栈溢出:How do I mock a class without an interface?

【讨论】:

  • 链接已损坏,似乎已移至此处:github.com
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-28
  • 1970-01-01
  • 2020-12-03
  • 1970-01-01
  • 2021-06-25
  • 1970-01-01
  • 2022-06-10
相关资源
最近更新 更多