We have discussed "Add Cosmos DB Built-in Roles to Resource Identities via Terraform to Allow Role Based Access to Data in Cosmos DB" in the previous post. Now that the data constributor roles are setup in Azure Cosmos DB, let's look at how to write a simple code to access, create Cosmos DB data using DefaultAzureCredential with C#.
The expection is to get document data created in Cosmos DB as similar to shown below.
Let's look at the step by step how we can use DefaultAzureCredential to work with Cosmos DB data.
First we need to refe to below NuGet packages. We need to refer Newtonsoft.Json as it is a prerequisite for Microsoft.Azure.Cosmos .
Then we can create DefaultAzureCredential and create aconnection to Cosmos DB as shown below.
Using the connection we can access a database and contianer in the Cosmos account.
Then we can dispose the connection.
Note that here the best practices like DI etc are not considered. The purpose was to show how to create a Cosmos DB account connection with DefaultAzureCredential. In real projects you should consider best practices to implement a singleton connection for Cosmos DB account. Full example code used in this post is available in GitHub.
No comments:
Post a Comment