Skip to content

[New article]: Create resource commands #2015

Closed
Closed
@JamesNK

Description

@JamesNK

Proposed topic or title

Create resource commands

Location in table of contents.

Custom integrations

Reason for the article

Aspire 9 introduces an API to add custom resource commands. People will want to know how to implement there own.

Mentioned in release notes here:

### Resource commands
The app host supports adding custom commands to resources. This is useful when you want to run custom commands on a resource.
> [!IMPORTANT]
> These .NET Aspire dashboard commands are only available when running the dashboard locally. They are not available when running the dashboard in Azure Container Apps.
The following example uses an extension method to add some additional commands.
```csharp
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddRedis("cache")
.WithClearCommand();
builder.AddProject<Projects.WebApplication1>("api")
.WithReference(cache)
.WaitFor(cache);
builder.Build().Run();
```
Custom commands can be added by calling the `WithCommand*` method and passing in the command to run:
```csharp
using Microsoft.Extensions.Diagnostics.HealthChecks;
using StackExchange.Redis;
public static class RedisCommandExtensions
{
public static IResourceBuilder<RedisResource> WithClearCommand(
this IResourceBuilder<RedisResource> builder)
{
builder.WithCommand(
"clear-cache",
"Clear Cache",
async context =>
{
var redisConnectionString = await builder.Resource.GetConnectionStringAsync() ??
throw new InvalidOperationException(
"Unable to get the Redis connection string.");
using var connection = ConnectionMultiplexer.Connect(redisConnectionString);
await connection.GetDatabase().ExecuteAsync("FLUSHALL");
return CommandResults.Success();
},
context =>
{
if (context.ResourceSnapshot.HealthStatus is HealthStatus.Healthy)
{
return ResourceCommandState.Enabled;
}
return ResourceCommandState.Disabled;
});
return builder;
}
}
```
These commands can be run from the dashboard:
:::image type="content" source="media/clear-cache-command.png" lightbox="media/clear-cache-command.png" alt-text="Clear cache command on dashboard":::

Article abstract

The article would talk about what resource commands are, show them in the dashbaord UI, and discuss examples of what custom commands can do.

It would then show code for an example custom command.

Relevant searches

No response

Metadata

Metadata

Assignees

Labels

doc-ideaIndicates issues that are suggestions for new topics [org][type][category]📦 release-9.0Used to track doc updates for release 9.0 of .NET Aspire.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions