Share via


Add Azure Cosmos DB to your app by using Visual Studio Connected Services

With Visual Studio, you can connect any of the following to Azure Cosmos DB by using the Connected Services feature:

  • .NET Framework console app
  • ASP.NET Model-View-Controller (MVC) (.NET Framework)
  • ASP.NET Core
  • .NET Core (including console app, WPF, Windows Forms, class library)
  • .NET Core Worker Role
  • Azure Functions
  • Universal Windows Platform App
  • Cordova

The connected service functionality adds all the needed references and connection code to your project, and modifies your configuration files appropriately.

Prerequisites

Connect to Azure Cosmos DB using Connected Services

Note

The local emulator for Azure Cosmos DB might reference a base image that uses a temporary license for Azure Cosmos DB. If the container doesn't start, check the Logs tab in the Containers* window for the Azure Cosmos DB container. If it mentions a PAL expiration issue, you need to get the latest base image for the local container. Run the following command from the console prompt: docker pull mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest. The license is periodically updated, and when it expires, refreshing to the newest container should solve the issue. You can view and report issues for the Azure Cosmos DB emulator at the Azure Cosmos DB emulator GitHub repo.

Next steps

Learn how to store secrets safely by following Safe storage of app secrets in development in ASP.NET Core. In particular, to read the connection string from the secrets store, you can add code as in Read the secret via the configuration API. The code might look like this, where builder is an instance of WebApplicationBuild that appears in Program.cs in ASP.NET Core project templates:

// New instance of CosmosClient class using a connection string
using CosmosClient client = new(
    connectionString: builder.Configuration["CosmosDBConnectionString"]
);

The CosmosClient provides access to Azure Cosmos DB functionality through its various methods. Once you have an instance of CosmosClient, you can create a NoSQL database by following this guide: Create a database in Azure Cosmos DB for NoSQL using .NET.