dotnet / aspire

An opinionated, cloud ready stack for building observable, production ready, distributed applications in .NET
https://learn.microsoft.com/dotnet/aspire
MIT License
3.37k stars 350 forks source link

Getting access to connectionstrings created by components in the AppHost before Run is called #2260

Open cisionmarkwalls opened 4 months ago

cisionmarkwalls commented 4 months ago

Perhaps this is possible and I'm just not finding it, but it would be immensely helpful if Aspire would allow me access to the connection strings for the components it creates. As an example:

var postgres = builder.AddPostgres("Sidecar");

If I could then get the connection string of that database before I started up the related services I could run EF migrations on those databases and pre-seed data into the database.

I have tried a couple of ways to get access to it before builder.Run() like:

NpgsqlEntityFrameworkCorePostgreSQLSettings settings = new();
var typeSpecificSectionName = $"Aspire:Npgsql:EntityFrameworkCore:PostgreSQL:{typeof(CDSContext).Name}";
var connection = builder.Configuration.GetSection(typeSpecificSectionName);
connection.Bind(settings);

I've also tried digging into the postgres.Resources object itself to see if I can find it before "Run" is called, but I don't think the connection string exists before that.

Is there a reason it can't be created before the associated services are started?

davidfowl commented 4 months ago

Aspire would allow me access to the connection strings for the components it creates. As an example:

Resource not componet. Components exist in the application projects, resources exist in the app host.

If I could then get the connection string of that database before I started up the related services I could run EF migrations on those databases and pre-seed data into the database.

https://github.com/dotnet/aspire/issues/398

This is the uber migration issue being looked at by @JamesNK. I'd suggest looking at that issue for the migrations problem. There's also a bigger database for local dev issue here https://github.com/dotnet/aspire/issues/1899.

Is there a reason it can't be created before the associated services are started?

Because you have to know the port to generate a connection string. We don't know the port until the service (well proxy) is running.

davidfowl commented 4 months ago

When you have a resource builder (your reference to postgres) you can do this:

postgres.Resource.GetConnectionString()

That will throw if the ports aren't yet allocated. You can't really sanely today run migration logic in the app host. Though there are attempts.