I am trying to add multiple DbContext instances in app, which is launched with .NET Aspire. I also want those separate contexts to have configuration available (in this case to have migration history tables in different schemas). Lastly, in Production environments, the app may be launched without .NET Aspire.
I have looked into Microsoft documentation. The problem I see here is that it looks like database configuration to DI container needs to be changed:
Before:
builder.Services.AddDbContext<ContextA>(options => options.UseSqlServer("MY_CONNECTION_STRING"), sqlServerOptions =>
{
sqlServerOptions.MigrationsHistoryTable("__EFMigrationsHistory", ContextA.Schema);
}));
builder.Services.AddDbContext<ContextB>(options => options.UseSqlServer("MY_CONNECTION_STRING"), sqlServerOptions =>
{
sqlServerOptions.MigrationsHistoryTable("__EFMigrationsHistory", ContextB.Schema);
}));
After:
builder.AddSqlServerDbContext<ContextA>("NAME_FROM_ASPIRE", options =>
{
options.????? // No way for me to change required SQL server options
});
builder.AddSqlServerDbContext<ContextB>("NAME_FROM_ASPIRE", options =>
{
options.????? // No way for me to change required SQL server options
});
There are several issues with this change:
- I can't do configuration to set up SQL server the way I want it.
- This will not work if app is not deployed using Aspire generated manifest, but instead if Aspire is only used for local development ("NAME_FROM_ASPIRE" will not really exist if Aspire is not used).
Ideally, I would only want Aspire to add SQL Server docker image with a volume, that runs on concrete port and let the app itself decide, how context should be set up (If I misconfigure in DistributedApplicationBuilder, that is on me!)
However, the following code didn't work (I can't see external ports exposed on Docker, SQL management programs can't connect to Database, .NET app says "Connection refused"):
var password = builder.AddParameter("SqlServerPassword");
var db = builder.AddSqlServer("database", password: password, port: 1434)
.WithVolume("data")
.AddDatabase("NAME_FROM_ASPIRE");
var app = builder.AddProject<Projects.MyApp>("app")
.WithReference("db");
What am I doing wrong?
AddSqlServerdoes configure databases but does nothing about any ORM entities, migrations or mappings