How to Start or Stop resources in Aspire by code

You may wanted to Start or Stop some resources during the tests with Aspire – by example when using DistributedApplicationTestingBuilder. Unfortunately, there’s no easy API for now, but you can do it (without reflection) but you have to use at least Aspire 9.1.

1. Obtain the IResource

// DistributedApplication app;
var applicationModel = app.Services.GetRequiredService<DistributedApplicationModel>();
var resources = applicationModel.Resources;
var resource = resources.SingleOrDefault(r => string.Equals(r.Name, resourceName, StringComparison.OrdinalIgnoreCase));

2. Get the ResourceId

// Asking for any state give us back the resourceId like "resource-x1cd1sd"
var eventResource = await App.ResourceNotifications.WaitForResourceAsync(resourceName, _ => true);
var resourceId = eventResource.ResourceId;

3. Get the ResourceCommandAnnotation « resource-start » or « resource-stop » (internal KnownResourceCommands)

if (!resource.TryGetAnnotationsOfType<ResourceCommandAnnotation>(out var commands))
{
    throw new Exception("Cannot get ResourceCommandAnnotations, use at least Aspire 9.1");
}

var commandName = "resource-start"; // resource-stop, resource-restart
var resourceCommandAnnotation = commands.First(a => a.Name == commandName);

4. Execute the command

 var result = await resourceCommandAnnotation.ExecuteCommand(new ExecuteCommandContext
 {
     ServiceProvider = app.Services,
     ResourceName = resourceId,
     CancellationToken = CancellationToken.None
 });

 if (!result.Success)
 {
     throw new Exception(result.ErrorMessage);
 }

5. Check the Status

// waiting for Start
await app.ResourceNotifications.WaitForResourceAsync(resourceName, KnownResourceStates.Running);

// waiting for Stop
await app.ResourceNotifications.WaitForResourceAsync(resourceName, KnownResourceStates.TerminalStates);

Et voilà !

Ce contenu a été publié dans Non classé. Vous pouvez le mettre en favoris avec ce permalien.