Working with Database in .NET Aspire
April 05, 2024 by Anuraj
AspNetCore Aspire CloudNative MongoDb
In this blog post, we’ll explore how we can work with Mongo databases in .NET Aspire. For working with Mongo database, we need to run Docker desktop. First we need to launch Docker desktop.
First we need to modify the Weatherforecast.AppHost
project and associate the Mongo database reference with API.
This will configure Mongo database with connection mongodb
and with weatherforecast
database. Next we need to add Aspire.MongoDB.Driver
nuget package to the API Application. We can do it by running the command - dotnet add package Aspire.MongoDB.Driver --version 8.0.0-preview.4.24156.9
. Once we added the nuget package, we can modify the code like this.
The AddMongoDBClient()
method will inject IMongoClient
interface which we can use it in the controller classes or Minimal API action methods. And we can use IMongoClient
interface to interact with Mongo database. Here is the code which will insert the weatherforecasts to database.
Now we are ready to run the application. If we are not running Docker we will get an error like this.
Run the Docker desktop to fix the issue and run the application again. Then we can browse the Aspire Dashboard.
In the dashboard we can see the Mongo service. If we notice, it is not exposing any ports. To access the database and view the collections we need configure any Mongo Database explorer tools. Aspire comes with MongoExpress
, we can modify the Aspire host like this.
Now run the application again and we will be able to see Mongo Express container running as well.
We can click on the Web Application to run the Angular application which will insert the Weather forecast array to the Mongo database. Then we can click on the Mongo Express URL which will open Mongo Express console and we can check the Mongo database, collections and values.
The application will reset the Mongo databases every time when we run the application every time. To fix the issue, we need to configure docker volume. We can configure it using WithVolume
option. Here is the updated code.
Run the application - we will be able to see the data in the Mongo database.
This way we can implement Mongo databases in Aspire. We can use the IMongoClient
interface to interact with the Mongo Database from ASP.NET Core C# code.
Happy Programming
Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub