.NET Azure Functions 中的依赖注入 - Azure Cosmos DB 客户端

Cie*_*eja 5 dependency-injection azure azure-functions azure-cosmosdb

我在 Microsoft Docs 上阅读了一篇关于在 .NET Azure Functions 中使用依赖项注入的文章。

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

builder.Services.AddSingleton((s) => {
     return new CosmosClient(Environment.GetEnvironmentVariable("COSMOSDB_CONNECTIONSTRING"));
    });
Run Code Online (Sandbox Code Playgroud)

问题是,如何在我的函数中使用 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 Code Online (Sandbox Code Playgroud)

Mat*_*int 6

你不具备使用的接口。你可以直接注入CosmosClient

在 Cosmos 客户端示例目录中有一个示例,其中包含以下代码:

private CosmosClient cosmosClient;
public AzureFunctionsCosmosClient(CosmosClient cosmosClient)
{
    this.cosmosClient = cosmosClient;
}
Run Code Online (Sandbox Code Playgroud)

对于测试,似乎创建此客户端的团队已决定采用将所有内容抽象/虚拟化的方法,以允许模拟框架根据需要覆盖方法。这在issue #303 中有所涉及。另请参阅堆栈溢出:如何在没有接口的情况下模拟类?

  • 链接已损坏,似乎已移至此处:[github.com](https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/Microsoft.Azure.Cosmos.Samples/Usage/AzureFunctions/AzureFunctionsCosmosClient 。CS) (2认同)