简体   繁体   中英

Dependency injection in .NET Azure Functions - Azure Cosmos DB Client

I read an article on Microsoft Docs about using dependency injection in .NET Azure Functions .

Everything works fine, as you can see in the article, it registers CosmosClient

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

The question is, how can I use Cosmos Client in my function? I do not want to create every time instance of 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;
    }
}

You don't have to use an interface. You can just inject the CosmosClient directly.

There's an example of this in the Cosmos client samples directory which includes the following code:

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

For testing, it seems the team creating this client has decided on the approach of making everything abstract/virtual to allow mocking frameworks to override methods as needed. This is touched on in issue #303 . See also on Stack Overflow: How do I mock a class without an interface?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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