.netasp.net-mvcdotnet-aspire

Setting up Multiple ASP.NET MVC Endpoints with a Single SQL Server Connection in Aspire


I recently attended .NET Conf 2023 where Aspire in .NET was introduced. I am working on a project and need guidance on how to set up multiple endpoints in a solution using Aspire. Currently, all three endpoints are connecting to a local SQL Server.

I want to modify the configuration so that all three endpoints connect to a single SQL Server. I would like to establish a dependency between these three endpoints and the SQL Server, making it easy to launch all three endpoints simultaneously. The endpoints are of type MVC ASP.NET.

My AppHost program.cs code :

var builder = DistributedApplication.CreateBuilder(args);

builder.AddProject<Projects.CarRental_EndPoint_Admin_Web>("admin");

builder.AddProject<Projects.CarRental_EndPoint_Renter_Web>("renter");

builder.AddProject<Projects.CarRenter_EndPoint_Rentor_Web>("rentor");

builder.Build().Run();
  1. How can I configure a shared SQL Server connection that serves as a dependency for all three endpoints?
  2. Once the SQL Server dependency is established, how can I access and use it within each endpoint's code?

Solution

  • just go ahead to code.

    AppHost Program.cs:

    var builder = DistributedApplication.CreateBuilder(args);
    
    var sql = builder.AddSqlServerContainer("sql",password:"Str0ngP@ssW0rd",port:12345).AddDatabase("CarRental");
    
    var backend = builder.AddProject<Projects.CarRental_EndPoint_API>("backend").WithReference(sql);
    
    builder.AddProject<Projects.CarRental_EndPoint_Admin_Web>("frontendadmin").WithReference(backend);
    
    builder.AddProject<Projects.CarRental_Persistence>("database").WithReference(sql);
    
    builder.Build().Run();
    

    and add builder.AddSqlServerDbContext<DataBaseContext>("CarRental"); to my endpoints.