Clone, run, and explore this sample
This sample demonstrates how to write custom resources for Aspire hosting integrations. This is useful when you want to integrate something into the Aspire development experience as a resource that isn't an executable or container. Custom resources can particpate in the Aspire development experience, including the dashboard, and can be used to integrate with other tools or services.
The entry point that composes every resource and dependency in this sample's distributed application.
using CustomResources.AppHost;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;
var builder = DistributedApplication.CreateBuilder(args);
builder.AddTalkingClock("talking-clock");
builder.AddTestResource("test");
builder.OnBeforeStart(static (@event, cancellationToken) =>{ var logger = @event.Services.GetRequiredService<ILoggerFactory>() .CreateLogger("CustomResources.AppHost");
logger.LogInformation("Starting custom resources sample with {ResourceCount} resources.", @event.Model.Resources.Count);
return Task.CompletedTask;});
builder.Eventing.Subscribe<AfterResourcesCreatedEvent>(static (@event, cancellationToken) =>{ var logger = @event.Services.GetRequiredService<ILoggerFactory>() .CreateLogger("CustomResources.AppHost");
logger.LogInformation("Custom resources sample created {ResourceCount} resources.", @event.Model.Resources.Count);
return Task.CompletedTask;});
builder.Build().Run();Custom resources are defined using C# and generally consist of a class that implements the IResource interface and some extension methods to enable adding them to an IDistributedApplicationBuilder. Custom resources can publish and respond to events to give them "life" and allow them to interact with the rest of the Aspire application.
In this sample, we define a TalkingClock custom resource that spawns child ClockHand resources that tick on and off every second. We also define a TestResource custom resource that simply cycles through a set of states.
Read more about the Aspire resource model here.
Prerequisites
Section titled PrerequisitesRunning the app
Section titled Running the appIf using the Aspire CLI, run aspire run from this directory.
If using VS Code, open this directory as a workspace and launch the CustomResources.AppHost project using either the Aspire or C# debuggers.
If using Visual Studio, open the solution file CustomResources.slnx and launch/debug the CustomResources.AppHost project.
If using the .NET CLI, run dotnet run from the CustomResources.AppHost directory.