microsoft / microsoft/aspire

Add `WithEnvironmentFromConfiguration` as an API to forward env var

Open
#11,948 1 comment 3 reactions 0 assignees View on GitHub
area-app-model
Dominant language
C#
Stars
6.3k
Forks
991
Avg merge
2d 15h
Merged PRs (30d)
196

Description

## Background and Motivation

The `WithEnvironment` API exists with likely the most overloads of all APIs in Aspire. I'm proposing another API that forwards env vars, verbatim from configuration to a target resource. No value is required, as it's pulled from configuration. The `name` is the env var key from configuration.

## Proposed API

```diff
namespace Aspire.Hosting;

public static class ResourceBuilderExtensions
{
+ public static IResourceBuilder WithEnvironmentFromConfiguration(
+ this IResourceBuilder builder,
+ string name) where TResource : IResourceWithEnvironment;
}
```

## Usage Examples

Here's a simple implementation example:

```cs
///
/// Forwards an environment variable from the application configuration to the underlying
///
/// The resource builder.
/// The environment variable name.
/// The resource type.
/// A reference to the .
public static IResourceBuilder WithEnvironmentFromConfiguration(
this IResourceBuilder builder,
string name) where TResource : IResourceWithEnvironment
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentException.ThrowIfNullOrWhiteSpace(name);

return builder.WithEnvironment(
name,
builder.ApplicationBuilder.Configuration.GetValue(name));
}
```

An example usage of this API would be:

```cs
var builder = DistributedApplication.CreateBuilder(args);

// Complete workflow:
// - Run → npm run dev
// - Deploy → netlify deploy
builder.AddNpmApp("sample", "../sample-site", "dev")
.WithHttpEndpoint(targetPort: 4321)
.WithEnvironmentFromConfiguration("NETLIFY_AUTH_TOKEN")
.PublishAsNetlifySite(new NetlifyDeployOptions() { Dir = "dist" });

builder.Build().Run();
```

## Alternative Designs

I haven't considered any.

## Risks

None that come to mind.

Contributor guide

Open the contributing guide

Research direction

Start by locating the existing WithEnvironment overloads and the proposed ResourceBuilderExtensions entry point, then review how builder.ApplicationBuilder.Configuration is accessed. Done means the new API forwards the named configuration value to the target resource while preserving the builder behavior; check the project’s existing tests for related environment APIs.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
backend-api-design
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.