aspirant-project / aspirant

Extensions for .NET Aspire
MIT License
57 stars 5 forks source link

Add `GetXXX` extension methods on `IDistributedApplicationBuilder` #7

Open DamianEdwards opened 3 months ago

DamianEdwards commented 3 months ago

Make it easy to get an IResourceBuilder<TResource> for the various TResource types on IDistributedApplicationBuilder and IDistributedApplicationTestingBuilder, e.g.:

var webfrontend = builder.GetProject("webfrontend");

if (builder.TryGetRedis("cache", var out cache)
{
    ...
}

This would be particularly useful in testing scenarios when using IDistributedApplicationTestingBuilder to mutate a resource during a test, e.g.:

[Fact]
public async Task GetWebResourceRootReturnsOkStatusCode()
{
    // Arrange
    var appHost = await DistributedApplicationTestingBuilder.CreateAsync<Projects.AspireApp8_AppHost>();
    var webfrontend = appHost.GetProject("webfrontend");
    webfrontend.WithEnvironment("ASPNETCORE_ENVIRONMENT", "Test");
    await using var app = await appHost.BuildAsync();
    await app.StartAsync();

    // Act
    var httpClient = app.CreateHttpClient("webfrontend");
    var response = await httpClient.GetAsync("/");

    // Assert
    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}

The Get variant should throw if the resource with the given name is not found or is the wrong type, whereas the TryGet variant would return false and assign the out parameter to null.

public static IResourceBuilder<ProjectResource> GetProject(this IDistributedApplicationBuilder builder, string resourceName);

public static bool TryGetProject(this IDistributedApplicationBuilder builder, string resourceName, IResourceBuilder<ProjectResource> resourceBuilder);

// Repeat for every resource type, e.g. Container, Executable, Parameter, Redis, etc.

// Repeated for IDistributedApplicationTestingBuilder