DistributedApplicationBuilderExtensions.CreateResourceBuilder<T> Method
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Creates a new resource builder based on the name of an existing resource.
public static Aspire.Hosting.ApplicationModel.IResourceBuilder<T> CreateResourceBuilder<T>(this Aspire.Hosting.IDistributedApplicationBuilder builder, string name) where T : Aspire.Hosting.ApplicationModel.IResource;
static member CreateResourceBuilder : Aspire.Hosting.IDistributedApplicationBuilder * string -> Aspire.Hosting.ApplicationModel.IResourceBuilder<'T (requires 'T :> Aspire.Hosting.ApplicationModel.IResource)> (requires 'T :> Aspire.Hosting.ApplicationModel.IResource)
<Extension()>
Public Function CreateResourceBuilder(Of T As IResource) (builder As IDistributedApplicationBuilder, name As String) As IResourceBuilder(Of T)
Type Parameters
- T
Type of resource.
Parameters
- builder
- IDistributedApplicationBuilder
The distributed application builder.
- name
- String
The name of an existing resource.
Returns
A resource builder.
Examples
In this example, the MyAspireApp.AppHost project has previously added a Redis resource named "cache" to the application host. The test project, MyAspireApp.AppHost.Tests, modifies that resource so that it sleeps instead of starting the Redis container. This allows the test case to verify that the application's health check returns an 'Unhealthy' status when the Redis resource is not available.
[Fact]
public async Task GetWebResourceHealthReturnsUnhealthyWhenRedisUnavailable()
{
// Arrange
var appHost = await DistributedApplicationTestingBuilder.CreateAsync<Projects.MyAspireApp_AppHost>();
// Get the "cache" resource and modify it to sleep for 1 day instead of starting Redis.
var redis = appHost.CreateResourceBuilder<ContainerResource>("cache"));
redis.WithEntrypoint("sleep 1d");
await using var app = await appHost.BuildAsync();
await app.StartAsync();
// Act
var httpClient = new HttpClient { BaseAddress = app.GetEndpoint("webfrontend") };
var response = await httpClient.GetAsync("/health");
// Assert
Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
Assert.Equal("Unhealthy", await response.Content.ReadAsStringAsync());
}
Remarks
The CreateResourceBuilder<T>(IDistributedApplicationBuilder, String) method is used to create an IResourceBuilder<T> for a specific resource where the original resource builder cannot be referenced. This does not create a new resource, but instead returns a resource builder for an existing resource based on its name.
This method is typically used when testing .NET Aspire applications where the original resource builder cannot be referenced directly. Using the CreateResourceBuilder<T>(IDistributedApplicationBuilder, String) method allows for easier mutation of resources within the test scenario.