Skip to main content

Bending Aspire to your will - Build a custom resource (Part 2)

In the previous part I defined ScalarResource and the OpenApiAnnotation, and services can opt in with WithOpenApi(). All data, no behaviour. Now I make Scalar actually start, find the documents, and tell the dashboard what it found.

Note: this post is part of a series about the demos from my session “Bending Aspire to your will”.


AddScalar: the behaviour lives in the extension method

public static IResourceBuilder<ScalarResource> AddScalar(
    this IDistributedApplicationBuilder builder,
    string name = "scalar",
    int? port = null)
{
    ArgumentNullException.ThrowIfNull(builder);

    var existing = builder.Resources.OfType<ScalarResource>().SingleOrDefault();
    if (existing is not null)
    {
        return builder.CreateResourceBuilder(existing);
    }

    builder.Services.TryAddEventingSubscriber<ScalarEndpointLogger>();

    var scalar = new ScalarResource(name);
    return builder.AddResource(scalar)
        .WithImage("scalarapi/api-reference", "0.6.22")
        .WithImageRegistry("docker.io")
        .WithHttpEndpoint(targetPort: 8080, port: port)
        .WithHttpHealthCheck("/health")
        .WithEnvironment(async context =>
        {
            // ... collect the OpenAPI documents, see below
        })
        .ExcludeFromManifest();
}

Step by step:

  • Singleton guard. If a ScalarResource already exists, return a builder for that one. Calling AddScalar() twice doesn't give you two containers.
  • TryAddEventingSubscriber registers the class that reacts to Scalar events. More on that below.
  • AddResource, WithImage, WithHttpEndpoint. This is the same you do for any container. port is optional, so you can pin it if you want a stable URL.
  • WithHttpHealthCheck("/health") gives the dashboard a real health state.
  • ExcludeFromManifest() keeps this developer tool out of publish and deploy.

Find the documents at start-up

The container needs a list of OpenAPI documents. That list can't be built when you call AddScalar(), because endpoints are only known when the AppHost starts. So the environment is a deferred callback:

.WithEnvironment(async context =>
{
    var sources = new List<ScalarEndpoint>();

    foreach (var resource in builder.Resources)
    {
        foreach (var document in resource.Annotations.OfType<OpenApiAnnotation>())
        {
            if (!document.Endpoint.Exists || (!document.Endpoint.IsHttp && !document.Endpoint.IsHttps))
            {
                throw new InvalidOperationException(
                    $"OpenAPI document '{document.Title}' on resource '{resource.Name}' must reference an existing HTTP or HTTPS endpoint '{document.Endpoint.EndpointName}'.");
            }

            var browserUrl = resource.Annotations
                .OfType<ResourceUrlAnnotation>()
                .FirstOrDefault(url =>
                    url.Endpoint?.EndpointName == document.Endpoint.EndpointName &&
                    url.DisplayLocation == UrlDisplayLocation.SummaryAndDetails)
                ?? throw new InvalidOperationException(
                    $"No browser-facing URL found for resource '{resource.Name}'.");

            var documentUrl = new Uri(new Uri(browserUrl.Url), document.Path);
            sources.Add(new ScalarEndpoint(document.Title, documentUrl.AbsoluteUri));
        }
    }

    if (sources.Count == 0)
    {
        throw new InvalidOperationException("Scalar requires at least one OpenAPI document. Declare one with WithOpenApi().");
    }

    context.EnvironmentVariables["API_REFERENCE_CONFIG"] =
        JsonSerializer.Serialize(new { sources }, JsonSerializerOptions.Web);

    // ... publish the discovery event, see below
})

The callback walks all resources, collects every OpenApiAnnotation, and serializes the result to the API_REFERENCE_CONFIG environment variable that Scalar reads. Two details:

  • It fails loudly. A document that points to a non-existing endpoint, or an AppHost without any WithOpenApi(), throws an exception with a message that says what to fix.
  • It uses the browser-facing URL. Scalar runs in your browser, so it needs the URL that your browser can reach, not the internal one. That is why the code looks for a ResourceUrlAnnotation.

Remark: two consequences of the browser-facing URL. First, the APIs need CORS. In aspire-shop, both the catalog service and the DB manager add an OpenApi CORS policy, but only in Development. Second, this connects back to Part 1: if you call context.Urls.Clear() on a resource that also has WithOpenApi() and don't add a URL for that endpoint again, AddScalar throws "No browser-facing URL found".

Talk back to the dashboard: events and state

A resource that silently does something is hard to debug. So Scalar publishes an event when it has discovered the documents:

public sealed record ScalarEndpointsDiscoveredEvent(
    ScalarResource Resource,
    IReadOnlyList<ScalarEndpoint> Endpoints) : IDistributedApplicationEvent;

The last part of the WithEnvironment callback publishes it:

await context.ExecutionContext.Services
    .GetRequiredService<IDistributedApplicationEventing>()
    .PublishAsync(
        new ScalarEndpointsDiscoveredEvent(scalar, sources.AsReadOnly()),
        context.CancellationToken);

And a subscriber, the class we registered with TryAddEventingSubscriber, reacts to it:

public sealed class ScalarEndpointLogger(ResourceNotificationService notification, ResourceLoggerService loggerService) : IDistributedApplicationEventingSubscriber
{
    public Task SubscribeAsync(
        IDistributedApplicationEventing eventing,
        DistributedApplicationExecutionContext executionContext,
        CancellationToken cancellationToken)
    {
        if (executionContext.IsRunMode)
        {
            eventing.Subscribe<ScalarEndpointsDiscoveredEvent>(async (@event, token) =>
            {
                var logger = loggerService.GetLogger(@event.Resource);
                logger.LogInformation("Scalar discovered {Count} OpenAPI endpoint(s).", @event.Endpoints.Count);

                foreach (var endpoint in @event.Endpoints)
                {
                    logger.LogInformation("OpenAPI endpoint {Title}: {Url}", endpoint.Title, endpoint.Url);

                    await notification.PublishUpdateAsync(@event.Resource, s => s with
                    {
                        State = new ResourceStateSnapshot("Endpoints discovered", KnownResourceStateStyles.Info)
                    });
                }
            });
        }

        return Task.CompletedTask;
    }
}

Two services do the work, and both are just services from the container:

  • ResourceNotificationService updates the state column of the resource. Scalar shows a custom state "Endpoints discovered" instead of only "Running".
  • ResourceLoggerService writes to the Logs tab of that resource, so you see which documents Scalar picked up.

The IsRunMode check makes sure this only happens when running locally.

Put it together

builder.AddScalar()
    .WithIconName("balloon")
    .WaitFor(basketService)
    .WaitFor(catalogService);

aspire run, and the dashboard shows a Scalar resource with its own icon, a custom state, and one URL that opens the API reference of every service that said WithOpenApi(). A new service with an OpenAPI document? Add one line to that service. Scalar doesn't change.

Tip: before you build your own, check if it already exists. There are over a hundred Aspire integrations (aspire add <integration>) and the Aspire Community Toolkit has community-built ones. The source of the built-in integrations is also a good place to learn how they do it.

That's it! A resource, an annotation, an extension method and an event subscriber. That's the whole pattern, and it works for any tool you want in your graph.

More information

Popular posts from this blog

Podman– Command execution failed with exit code 125

After updating WSL on one of the developer machines, Podman failed to work. When we took a look through Podman Desktop, we noticed that Podman had stopped running and returned the following error message: Error: Command execution failed with exit code 125 Here are the steps we tried to fix the issue: We started by running podman info to get some extra details on what could be wrong: >podman info OS: windows/amd64 provider: wsl version: 5.3.1 Cannot connect to Podman. Please verify your connection to the Linux system using `podman system connection list`, or try `podman machine init` and `podman machine start` to manage a new Linux VM Error: unable to connect to Podman socket: failed to connect: dial tcp 127.0.0.1:2655: connectex: No connection could be made because the target machine actively refused it. That makes sense as the podman VM was not running. Let’s check the VM: >podman machine list NAME         ...

Cache stampede: when our cache turned against us

While investigating some performance issues, we ran into an ASP.NET Core API that cached a fairly expensive aggregation query for 60 seconds. Under normal load, that was fine: one request rebuilds the cache, everyone else reads from it. Under peak load, dozens of requests would arrive in that same expiry window, all see a cache miss, and all fire the same expensive query in parallel. The database didn't like that. That was the moment when our caching layer stopped helping and started hurting. A burst of requests comes in at the same time, all miss the cache, and all go hammer the database or the downstream API at once. That's a cache stampede . The cache was supposed to protect our backend, and for a few hundred milliseconds it did the opposite. Why this happens IMemoryCache.GetOrCreate (and its async sibling) looks like it protects you, but it doesn't add any locking on its own. Look at the naive version: public async Task<Report> GetReportAsync(string key) ...

VS Code Planning mode

After the introduction of Plan mode in Visual Studio , it now also found its way into VS Code. Planning mode, or as I like to call it 'Hannibal mode', extends GitHub Copilot's Agent Mode capabilities to handle larger, multi-step coding tasks with a structured approach. Instead of jumping straight into code generation, Planning mode creates a detailed execution plan. If you want more details, have a look at my previous post . Putting plan mode into action VS Code takes a different approach compared to Visual Studio when using plan mode. Instead of a configuration setting that you can activate but have limited control over, planning is available as a separate chat mode/agent: I like this approach better than how Visual Studio does it as you have explicit control when plan mode is activated. Instead of immediately diving into execution, the plan agent creates a plan and asks some follow up questions: You can further edit the plan by clicking on ‘Open in Editor’: ...