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
ScalarResourcealready exists, return a builder for that one. CallingAddScalar()twice doesn't give you two containers. TryAddEventingSubscriberregisters the class that reacts to Scalar events. More on that below.AddResource,WithImage,WithHttpEndpoint. This is the same you do for any container.portis 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:
ResourceNotificationServiceupdates the state column of the resource. Scalar shows a custom state "Endpoints discovered" instead of only "Running".ResourceLoggerServicewrites 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.

