avatarShawn Shi

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2505

Abstract

<iframe class="gist-iframe" src="/gist/ShawnShiSS/ae699dbd386d0d5f0e536ffde4e33f08.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined"> </div> </div> </figure></iframe></div></div></figure><h2 id="550b">Part 2 — Cosmos DB Container Factory</h2><p id="d771">Particularly, we are utilizing a singleton instance of the Cosmos DB Client from the Azure Cosmos DB .NET SDK in line 47 to create the database if it does not already exist. Once we have the database, we loop through the containers from configuration values and ensure they are all created.</p> <figure id="60fb"> <div> <div>
            <iframe class="gist-iframe" src="/gist/ShawnShiSS/fb7c0f3e637a8b931d465f9dd2f2ad2f.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><h2 id="6ce2">Part 3 — Startup class in API Application</h2><p id="4109">In Configure Services method, we read the connection string from the Configuration and register a singleton instance of the Cosmos DB Container Factory.</p><p id="6ee4">In Configure method, we call the synchronous method EnsureCosmosDbIsCreated to auto create the database and the containers if they do not exist. I am also showing how to call an asynchronous extension method to seed the database. Both work equally, pick your coffee roast level!</p>
    <figure id="c2b1">
        <div>
          <div>
            
            <iframe class="gist-iframe" src="/gist/ShawnShiSS/768ffec1dd3dcad4f8368af604fa4719.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="de2d">AddCosmosDb method is just another extension method for the service collection, see below:</p>
    <figure id="8728">
        <div>
          <div>
            
            <iframe class="gist-iframe" src="/gist/ShawnShiSS/0b6584392fc08bd844b41afe926a56e2.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><h2 id="d943">Final part — App Settings</h2><p id="9d3f">Whether you are running the API locally for development or on production, you will need the app settings, likely from JSON file. For example, appsettings.Development.j

Options

son for local development using Cosmos DB Emulator:</p> <figure id="cd8b"> <div> <div>

            <iframe class="gist-iframe" src="/gist/ShawnShiSS/e07417db1ecdd2babcafa31e00014a31.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><h1 id="8541">Conclusions</h1><p id="e8f5">There you go! You should now have everything required to run an API or Web project and see your Cosmos DB database and all containers created automatically, and seeded!</p><p id="fdca">Many thanks for reading. Cheers!</p><p id="8c7b">The sample code used in this article is from a <a href="https://github.com/ShawnShiSS/clean-architecture-azure-cosmos-db">GitHub starter project</a>, which follows Clean Architecture to organize the projects. This repo features Partitioned Repository Pattern using Azure Cosmos DB to build scalable backend service, REST API, Azure Functions, React SPA, etc.. Feel free to use the whole starter project or part of it to kick start your next exciting adventure!</p><p id="6d41">For more resources relevant to the project:</p><ul><li>GitHub repo: <a href="https://github.com/ShawnShiSS/clean-architecture-azure-cosmos-db"><i>Clean Architecture with partitioned repository pattern using Azure Cosmos DB</i></a></li><li>Article: <a href="https://readmedium.com/clean-architecture-with-partitioned-repository-pattern-using-azure-cosmos-db-62241854cbc5"><i>Clean Architecture — ASP.NET Core API using Partitioned Repository Pattern and Azure Cosmos DB</i></a></li><li>Article: <a href="https://readmedium.com/audit-log-using-partitioned-repository-pattern-with-cosmos-db-99b63de97e35"><i>Audit Log Using Partitioned Repository Pattern With Cosmos DB</i></a></li><li>Article: <a href="https://readmedium.com/clean-architecture-azure-functions-using-cosmos-db-ce7f521aa7b5"><i>Clean Architecture — Azure Functions Using Partitioned Repository with Cosmos DB</i></a></li><li>Article: <a href="https://readmedium.com/clean-architecture-best-exception-handling-with-consistent-responses-in-asp-net-core-api-b22b07a08e38"><i>Best Exception Handling with Consistent Responses in ASP.NET Core API</i></a></li><li>Article: <a href="https://readmedium.com/best-design-pattern-for-azure-cosmos-db-containers-factory-pattern-addff5628f8a"><i>Best Design Pattern for Azure Cosmos DB Containers — Factory Pattern</i></a></li></ul></article></body>

Clean Architecture — How to Auto-Create Cosmos DB Database and Containers on App Startup

Discussing how to automatically create an Azure Cosmos DB database and its containers on API application startup in Clean Architecture using ASP.NET Core.

UPDATE April 10, 2022: all projects in the GitHub repo have been upgraded to .NET 5.

Background

It is straightforward to create an Azure database and containers in Azure Portal. But if you are developing a new application using Cosmos DB Emulator, it will be nice to be able to delete the whole database and have it automatically re-created on the application start to get a clean slate. Also, if a new developer joins the team, he/she can just run the application and be all set to go, instead of having to manually create a database and containers (annoying!).

Image by Author, Cosmos DB icon from Microsoft

Prerequisites

Part 1 — Application Builder Extension Methods

This class defines the application builder extension methods which allow us to call them in the Configure() method in Startup class in the API project. The core piece is really straightforward:

  1. Get an instance of the Cosmos DB Container Factory
  2. Call EnsureDbSetupAsync() method. We need to explicitly wait for it to complete, since EnsureDbSetupAsync is an asynchronous method and we want to make the whole extension method a synchronous method. I will cover EnsureDbSetupAsync() method in a sec.

I’ve also included an asynchronous extension method to automatically seed the initial database if you are interested in how it can be done. Pick your own apples!

Part 2 — Cosmos DB Container Factory

Particularly, we are utilizing a singleton instance of the Cosmos DB Client from the Azure Cosmos DB .NET SDK in line 47 to create the database if it does not already exist. Once we have the database, we loop through the containers from configuration values and ensure they are all created.

Part 3 — Startup class in API Application

In Configure Services method, we read the connection string from the Configuration and register a singleton instance of the Cosmos DB Container Factory.

In Configure method, we call the synchronous method EnsureCosmosDbIsCreated to auto create the database and the containers if they do not exist. I am also showing how to call an asynchronous extension method to seed the database. Both work equally, pick your coffee roast level!

AddCosmosDb method is just another extension method for the service collection, see below:

Final part — App Settings

Whether you are running the API locally for development or on production, you will need the app settings, likely from JSON file. For example, appsettings.Development.json for local development using Cosmos DB Emulator:

Conclusions

There you go! You should now have everything required to run an API or Web project and see your Cosmos DB database and all containers created automatically, and seeded!

Many thanks for reading. Cheers!

The sample code used in this article is from a GitHub starter project, which follows Clean Architecture to organize the projects. This repo features Partitioned Repository Pattern using Azure Cosmos DB to build scalable backend service, REST API, Azure Functions, React SPA, etc.. Feel free to use the whole starter project or part of it to kick start your next exciting adventure!

For more resources relevant to the project:

Azure Cosmos Db
Seeding
Factory Pattern
Aspnetcore
Auto Create
Recommended from ReadMedium