azuredependency-injectionazure-functionsazure-cosmosdb

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;
    }
}

Solution

  • 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?