liveBook · Manning

AddResource

As explained in Building Distributed Applications that Work

AddResource is an Aspire builder method that registers a resource with the application orchestrator.

AddResource registers a resource instance with the Aspire orchestrator. Like AddProject, it makes something available as a hosted service, but it is not limited to projects. section 2.4

Use it when registration needs a custom resource object. For a Keycloak container, a KeycloakResource carries a client secret that can be passed into container configuration and a client application. AddContainer offers less control over such additional parameters. section 2.4

Listing 2.1 Adding a Keycloak container
public static IResourceBuilder<KeycloakResource>
    AddKeycloakContainer(
    this IDistributedApplicationBuilder builder,
    string name,
    int? port = null,
    string? tag = null)
{
    var keycloakContainer = new KeycloakResource(name)   #1
    {
        ClientSecret = "some_secret"
    };

    var keycloak = builder
        .AddResource(keycloakContainer)    #2
        .WithAnnotation(new ContainerImageAnnotation    #3
        {
            Registry = "quay.io",
            Image = "keycloak/keycloak",
            Tag = tag ?? "latest"
         })
        .WithHttpEndpoint(port: port,    #4
            targetPort: 8080)
        .WithEnvironment("KEYCLOAK_ADMIN", "admin")   #5
        .WithEnvironment("KEYCLOAK_ADMIN_PASSWORD",
            "admin")
        .WithEnvironment("WEBAPP_CLIENT_SECRET",
            keycloakContainer.ClientSecret);

    if (builder.ExecutionContext.IsRunMode)    #6
    {
        keycloak.WithArgs("start-dev");
    }
    else
    {
        keycloak.WithArgs("start");
    }

    return keycloak;
}

The AddKeycloakContainer extension creates the custom resource, registers it with AddResource, then configures its image, endpoint, and environment variables. section 2.4

How Building Distributed Applications that Work covers it

How deep it goes
Works through registration in a C# extension method and contrasts AddContainer; does not detail AddResource internals.
Examples
Uses a KeycloakResource with a client secret, followed by Docker image, HTTP endpoint, and environment-variable configuration.
What you can do after
Build it from scratch as an Aspire extension method that registers a custom container resource and configures it.
How it connects
Connects AddResource to AddProject, AddContainer, ContainerResource, container image annotations, endpoints, and environment variables.

This explainer was generated by Manning's knowledge graph from the text of Building Distributed Applications that Work. The section links point to the parts of the book it draws on.