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.61k stars 401 forks source link

Pass own endpoint to a project as environment variable #3561

Open davidfowl opened 5 months ago

davidfowl commented 5 months ago

Discussed in https://github.com/dotnet/aspire/discussions/3522

Originally posted by **Kralizek** April 9, 2024 I need to set two environment variables for a project to be able to run correctly: one is the address of another service, the other is the address of the same service. ```csharp var auth = builder.AddProject("auth") .WithReference(db) .WithReference(legacyDb); var admin = builder.AddProject("admin") .WithEnvironment("AdminUi__AuthorityUrl", auth.GetEndpoint("http")) .WithEnvironment("AdminUi__UiUrl", "http://localhost:5278") // Copied from launchSettings.json .WithReference(db); ``` Is there a better way than this? Something that doesn't create a magic string coupling? Ideally I'd love the possibility to do something like ```csharp var admin = builder.AddProject("admin") .WithEnvironment("AdminUi__AuthorityUrl", auth.GetEndpoint("http")) .WithEnvironment("AdminUi__UiUrl", t => t.GetEndpoint("http")) .WithReference(db); ```
mitchdenny commented 4 months ago

I think this could be useful in this situation where people might want to specify configuration in the appsettings.json but need to pass in the Url via an environment variable to override. For example: https://github.com/dotnet/aspire/issues/3695

WhitWaldo commented 4 months ago

I'm partial to using GetEndpoint to avoid assigning static ports to projects locally while still being able to access the endpoints used for non-HttpClient scenarios (e.g. populating links to other localhost projects in Blazor pages).

davidfowl commented 4 months ago

Simplest way to do this is to break up your fluent API calls:

var auth = builder.AddProject<AuthService>("auth")
                 .WithReference(db)
                 .WithReference(legacyDb);

var admin = builder.AddProject<Admin>("admin")
                   .WithEnvironment("AdminUi__AuthorityUrl", auth.GetEndpoint("http"))
                   .WithReference(db);

admin.WithEnvironment(context =>
{
    context.EnvironmentVariables["AdminUi__UiUrl"] = admin.GetEndpoint("http");
})