Skip to main content

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

I spend a lot of time testing and debugging APIs, and so do my AI agents. Lately I notice that my agents lose time and tokens on it. They look for the right port, guess at endpoints, fight with a terminal, and try to get the database back into a known state. Every run starts with the same detective work.

So for this series of posts I picked one scenario and I’m sticking with it: the API-testing loop. The goal is to adapt Aspire so that I (and my agents) can debug and test easily and efficiently.

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

Every API in my AppHost has its own OpenAPI document, and every API can have its own UI. I want one API reference for the whole graph. Scalar runs as a container, so it fits in Aspire as a resource. The question is how you build a custom resource that feels like it belongs there.

The naive way is a Scalar container with a hand-written list of API URLs. It works, but it is one more list I have to maintain, and the services have no say in it. What I want is this:

catalogService.WithOpenApi(endpointName: "https", title: "Catalog API");
builder.AddScalar().WaitFor(catalogService);

Services declare that they have an OpenAPI document. Scalar finds them. Neither knows more than that about the other.

Everything is a resource

In Aspire, everything in the graph is a resource: containers, executables, projects, parameters and connection strings. They are built from a small set of base types (ContainerResource, ExecutableResource, ProjectResource, ParameterResource, ConnectionStringResource) and interfaces that describe what a resource can do (IResourceWithEndpoints, IResourceWithConnectionString, IResourceWithEnvironment, IResourceWithWaitSupport, ...).

The most important rule to apply is that a resource class is inert. It is data. No side effects in the constructor. The behaviour lives next to it:

  • Extension methods: Add* creates a resource, With* configures it.
  • Annotations: typed metadata. URLs, commands, icons and health checks are all annotations.
  • Lifecycle events: the moments where your code may run, like before start or when ready.

Previous parts of this Aspire blog series used the annotation-based APIs without you noticing. WithIconName, WithUrls and WithCommand are all extension methods that add an annotation.

Classify before you code

Before I write a line, I answer four questions. Resources don't fit in one inheritance tree, so I look at four axes instead:

Axis Ask Examples
Resource shape What does it represent? Container, Executable, External reference, Sidecar
Lifecycle mode When does it exist? Run, Publish/Deploy, Both, Mode-agnostic
Integration role What job does it do? Dependency, Workload, Companion, Bridge, Controller
Structure How is it wired? Standalone, Parent-child, Facade, Singleton, Overlay

PostgreSQL, for example, is a container-backed service, a dependency, and has child and companion structures, all at once.

For Scalar, the answers are:

  • Shape: a tool container, so ContainerResource.
  • Lifecycle: run-only. It is always excluded from the manifest.
  • Role: a standalone developer tool.
  • Structure: a singleton utility with annotation-driven discovery.

That last answer gives me the naming. If a tool belongs to one parent, you write With{Tool} on that parent. If it serves many resources, you write Add{Tool} on the builder. Scalar serves many, so it's AddScalar().

The resource: one line

public sealed class ScalarResource(string name) : ContainerResource(name);

That's it. No logic, no constructor side effects.

The annotation: what a service offers

The service needs a way to say "I have an OpenAPI document". That is an annotation:

public sealed record OpenApiAnnotation(EndpointReference Endpoint, string Path, string Title) : IResourceAnnotation;

And an extension method to add it:

public static IResourceBuilder<T> WithOpenApi<T>(
    this IResourceBuilder<T> builder,
    string path = "/openapi/v1.json",
    string endpointName = "http",
    string? title = null) where T : IResourceWithEndpoints
{
    ArgumentNullException.ThrowIfNull(builder);
    ArgumentException.ThrowIfNullOrWhiteSpace(path);
    ArgumentException.ThrowIfNullOrWhiteSpace(endpointName);

    if (!path.StartsWith('/') || path.StartsWith("//", StringComparison.Ordinal) || path.Contains('\\')
        || !Uri.TryCreate(path, UriKind.Relative, out _))
    {
        throw new ArgumentException("The OpenAPI path must be an absolute URL path, such as /openapi/v1.json.", nameof(path));
    }

    if (title is not null)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(title);
    }

    return builder.WithAnnotation(new OpenApiAnnotation(
        builder.GetEndpoint(endpointName), path, title ?? builder.Resource.Name));
}

Most of this is argument validation. The core is the last statement: one annotation with an endpoint reference, a path and a title. The generic constraint where T : IResourceWithEndpoints means you can only call it on resources that actually have endpoints.

Now the services opt in:

catalogService.WithOpenApi(endpointName: "https", title: "Catalog API");
catalogDbManager.WithOpenApi(endpointName: "https", title: "Catalog DB Manager API");

Remark: services declare what they offer with an annotation and know nothing about Scalar. If I replace Scalar with another tool next year, the services don't change.

That's it! At this point nothing runs. A resource class, an annotation and an extension method are only data. In the next part, I add the behaviour: AddScalar, the container, and the way it discovers the documents when the AppHost starts.

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’: ...