Development API Using Microsoft Aspire
Usually, any backend API project needs at least a database server. In my test project, I needed a PostgreSQL database and RabbitMQ. Maybe later, I will add Redis.
How can you solve the environment setup problem? You can install the necessary servers locally and use them. But that is not a very good solution: service versions often change, and each project requires something specific. That is why I have been using Docker and Docker Compose for a long time. The only downside is that you need to create compose files for each project. It is not too difficult, but you can get by without it.
I decided to try MS Aspire for this purpose.
- Create a new, empty Aspire project. I recommend using the latest versions to avoid problems. The project is also created with some useful extensions by default: enable telemetry and enable health checks.
2. Add the necessary packages to this project. In my case, these are:
dotnet add package Aspire.Hosting.PostgreSQL
dotnet add package Aspire.Hosting.RabbitMQ
3. Add code that describes our infrastructure:
var builder = DistributedApplication.CreateBuilder(args);
var username = builder.AddParameter("username", secret: true);
var password = builder.AddParameter("password", secret: true);
var postgres = builder.AddPostgres("postgres", username, password)
.WithImage("postgres:13-alpine")
.WithDataBindMount(source: @"..\..\Data\PostgreSQL\Data", isReadOnly: false)
.WithPgAdmin();
var postgresdb = postgres.AddDatabase("event-sourcing");
var rabbitUsername = builder.AddParameter("rabbit-username", secret: true);
var rabbitPassword = builder.AddParameter("rabbit-password", secret: true);
var rabbitmq = builder.AddRabbitMQ("rabbit", rabbitUsername, rabbitPassword)
.WithDataBindMount(source: @"..\..\Data\RabbitMQ\Data", isReadOnly: false)
.WithManagementPlugin();
builder.AddProject<Projects.EventSourcing>("api")
.WithReference(postgresdb, "DbConnection")
.WithReference(rabbitmq, "Rabbit")
.WaitFor(postgresdb)
.WaitFor(rabbitmq);
builder.Build().Run();
Pay attention to the connection strings. After a lot of trial and error, I explicitly set them in the .WithReference calls. I also added PgAdmin and mounted data folders to my local disk — I simply prefer it that way.
That is all. Make the Aspire project the startup project and run it.
What is the result? We get the needed working infrastructure with minimal effort. You can start or stop the entire infrastructure with one command. As a bonus, we get the Aspire dashboard with useful features, where you can monitor our API online.
The only downside is that Aspire is not suitable for production. It would be nice if it could at least generate compose files based on the programmed configuration.
Full code you can find on my Github: https://github.com/XHunter74/EventsSourcing