Aspire, Sql Server Docker Container and multiple Connections strings

Aspire is the new visualizer – see https://github.com/dotnet/aspire

When creating a Docker container with Sql Server , the connection that is returned is without database – means that , usually, is connecting to the master.

That’s not that we usually want, so the following code is means that WebAPI will be connected to master

var builder = DistributedApplication.CreateBuilder(args);
var rb= builder.AddSqlServerContainer("Db2Gui", "<YourStrong@Passw0rd>");
builder.AddProject<Projects.ExampleWebAPI>(nameof(Projects.ExampleWebAPI))
   .WithReference(rb)
    ;

Instead , do what they do – but add the database

var builder = DistributedApplication.CreateBuilder(args);

var rb= builder.AddSqlServerContainer("Db2Gui", "<YourStrong@Passw0rd>");

builder.AddProject<Projects.ExampleWebAPI>(nameof(Projects.ExampleWebAPI))
    .WithEnvironment(ctx=>
    {
        var connectionStringName = $"ConnectionStrings__";
        var res=rb.Resource;
        var cn = res.GetConnectionString();
        ctx.EnvironmentVariables[connectionStringName+ "ApplicationDBContext"] = cn+ $";database=tests;";
        ctx.EnvironmentVariables[connectionStringName+ "NorthwindDBContext"] = cn + $";database=northwind;";
        ctx.EnvironmentVariables[connectionStringName+ "PubsDBContext"] = cn + $";database=pubs;";
    })
    //.WithReference(rb, "")
    ;

It is true that you can make the following :

builder.AddProject<Projects.ExampleWebAPI>(nameof(Projects.ExampleWebAPI))
    .WithReference(rb.AddDatabase("tests"), "ApplicationDBContext")
    .WithReference(rb.AddDatabase("northwind"), "NorthwindDBContext")
    .WithReference(rb.AddDatabase("pubs"), "PubsDBContext")
    .WithReference(rb.AddDatabase("NotCreated"), "NotCreated")

    ;

But it does not CREATE the database ( and it is a good thing …. EF EnsureCreated verifies JUST the existence of the database not of the tables within)
So thats why I prefer WithEnvironment rather than .WithReference(rb.AddDatabase