7

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;
    }
}
mskuratowski
  • 4,014
  • 15
  • 58
  • 109

1 Answers1

8

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?

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • 2
    Link broken, appears to have moved here: [github.com](https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/Microsoft.Azure.Cosmos.Samples/Usage/AzureFunctions/AzureFunctionsCosmosClient.cs) – Lance Aug 31 '21 at 14:23
  • where is the cosmosClient instance getting its connection string from? – Martin Meeser Jul 16 '22 at 21:25