我阅读了有关使用dependency injection in .NET Azure Functions的Microsoft文档的文章。
一切正常,如您在文章中所见,它注册了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;
}
}
答案 0 :(得分:4)
您没有使用界面。您可以直接注入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?