skip to content

In an Aspire AppHost, how do AddProject, AddContainer and AddExecutable differ, and when would you pick each one?

level: middleimportance: should knowfreq 42%

answer

  1. process, image, or host command
  2. launchSettings.json drives project endpoints
  3. AddContainer(name, image, tag)
  4. ContainerLifetime.Session is the default
  5. executables resolve through PATH

basics

~20 s

AddProject runs a referenced .NET project as a process and reads its launch profile for endpoints; AddContainer runs any image through Docker or Podman; AddExecutable runs any host command. All three share WithReference, WaitFor and WithEnvironment.

solid answer

~40 s

`AddProject<Projects.X>(name)` models a .NET project from the solution: Aspire runs it as a separate process and reads its `launchSettings.json` profile, and its Kestrel configuration, to create endpoints. `AddContainer(name, image, tag)` models an image the container runtime pulls and runs; you describe ports with `WithHttpEndpoint(targetPort: ...)`, data with `WithVolume` or `WithBindMount`, and it is removed when the AppHost stops unless you call `WithLifetime(ContainerLifetime.Persistent)`. `AddExecutable(name, command, workingDirectory, args)` models any process on the host, and the command must be on `PATH` or given as a full or `./` path. Integration methods such as `AddPostgres` and `AddRedis` are typed container resources with health checks and connection strings already built in, so you reach for raw `AddContainer` only when no integration exists.

code

csharp · 18 lines
csharp
var builder = DistributedApplication.CreateBuilder(args);

var cache = builder.AddRedis("cache")
    .WithLifetime(ContainerLifetime.Persistent);

var printer = builder.AddContainer("label-printer", "pizzashop/label-printer", "1.4")
    .WithHttpEndpoint(targetPort: 8080, name: "http");

var ovenSim = builder.AddExecutable(
        "oven-sim", "./ovensim", "../tools/oven-sim", "--speed", "fast")
    .WithHttpEndpoint(name: "http", env: "PORT");

builder.AddProject<Projects.PizzaShop_Api>("pizza-api")
    .WithReference(cache)
    .WithReference(ovenSim.GetEndpoint("http"))
    .WithEnvironment("LABEL_PRINTER_URL", printer.GetEndpoint("http"));

builder.Build().Run();

go deeper

for a junior

Recall the three Add methods and what each runs: a .NET project, a container image, or a host command.

for a middle

Explain where each kind gets its endpoints, what the Session and Persistent container lifetimes do, and why integrations beat raw AddContainer.

for a senior

Show judgement about when a persistent container or a host executable speeds up the inner loop and what state or security trade-off it brings.

for a principal

Weigh how far a team should model non-.NET tooling in the AppHost against keeping it in separate scripts, given that every resource also feeds publishing.

## Three base resource kinds Every resource in an Aspire AppHost has a name and a type. Most typed resources a developer meets, such as PostgreSQL or Redis, are specializations of three base kinds. Knowing the base kind tells you how the orchestrator runs the resource and which fluent methods apply. | | `AddProject` | `AddContainer` | `AddExecutable` | |---|---|---|---| | Resource type | `ProjectResource` | `ContainerResource` | `ExecutableResource` | | What runs | a .NET project as a host process | an OCI image in Docker or Podman | any command on the host | | Identity input | generated `Projects.X` type or a project path | image name and optional tag | command, working directory, arguments | | Endpoints | from `launchSettings.json` and Kestrel config | declared with `WithHttpEndpoint` or `WithEndpoint` | declared with `WithHttpEndpoint` | | OTLP settings for the dashboard | injected automatically | only after `WithOtlpExporter()` | only after `WithOtlpExporter()` | ## `AddProject` `builder.AddProject<Projects.PizzaShop_Api>("pizza-api")` is the normal way to add a .NET service. The generic type comes from the AppHost's `ProjectReference`; a non-generic overload takes a project path. Aspire reads the project's **launch profile** from `launchSettings.json` to find its URLs and environment variables, and turns each URL into an endpoint. Overloads accept a launch profile name, `null` to use none, or a `ProjectResourceOptions` callback. - The project runs as a separate process, not in a container, during `aspire run`. - It receives the OpenTelemetry settings that point it at the dashboard, so its logs, traces and metrics appear there. - `WithReplicas(n)` starts several instances of the same project behind that proxy. ## `AddContainer` `builder.AddContainer("label-printer", "pizzashop/label-printer", "1.4")` runs any image, here an in-house service that prints box labels. The image knows nothing about Aspire, so you describe it yourself: - `WithHttpEndpoint(targetPort: 8080, name: "http")` maps the container's port to a host port. - `WithEnvironment(...)` and `WithArgs(...)` set its environment and command-line arguments. - `WithVolume(...)` or `WithBindMount(...)` keep files outside the container. - `WithLifetime(ContainerLifetime.Persistent)` keeps the container running after the AppHost stops and reuses it next time; the default, `ContainerLifetime.Session`, creates it at start and removes it at shutdown. `AddDockerfile(name, contextPath)` is the sibling for an image Aspire should build from a local Dockerfile. Integration methods such as `AddPostgres` or `AddRedis` return container resources too, but they already pick the image, set the port, register health checks and expose a connection string, which is why you prefer them whenever one exists. ## `AddExecutable` `builder.AddExecutable("oven-sim", "./ovensim", "../tools/oven-sim", "--speed", "fast")` runs a command on the host; `WithHttpEndpoint(env: "PORT")` tells the process which port to listen on through an environment variable. As a security measure Aspire runs a bare command name only if it is found on `PATH`; a file in the working directory needs a full path or a `./` prefix. Typical uses: 1. A non-.NET tool or simulator that ships as a binary. 2. A script runner that has no dedicated integration. 3. A local CLI such as a tunnel or mock server during development. ## Shared behaviour All three accept the common annotations: `WithReference` to receive configuration, `WaitFor` and its siblings to order startup, `WithEnvironment` for extra variables, and `WithExplicitStart()` to keep a resource from starting automatically. The dashboard lists them side by side with state, logs and endpoints, whatever their kind. ## Choosing - Your own .NET service in the solution: `AddProject`. - A database, cache or broker with an Aspire integration: the integration's `Add*` method. - Any other image: `AddContainer`, or `AddDockerfile` when you build it locally. - A host tool that is neither: `AddExecutable`. ## Interview traps Three misunderstandings come up repeatedly. First, candidates assume `AddProject` containerizes the service during local runs; it does not, which is why a debugger attaches to it as to any local process. Container images for projects only appear when the app is published. Second, candidates confuse **data persistence** with **container persistence**: a data volume keeps files while the container is recreated, and a persistent lifetime keeps the container itself. Third, candidates expect any container to show telemetry in the dashboard automatically; projects get the OTLP settings by default, while a container or executable gets them only through `WithOtlpExporter()` and must still export OTLP itself, so an arbitrary image may contribute console logs alone.

  • What does WithLifetime(ContainerLifetime.Persistent) change compared with WithDataVolume()?
    `WithDataVolume` keeps the data directory in a named volume while the container itself is still removed and recreated each run. `ContainerLifetime.Persistent` keeps the container running after the AppHost stops and reuses it on the next run when its configuration still matches, which also saves the container's startup time on every run.
  • Why do you rarely call AddContainer for PostgreSQL or Redis?
    The hosting integrations' `AddPostgres` and `AddRedis` already choose the image and tag, set the target port, generate a password parameter, register health checks that `WaitFor` uses and expose a connection string for `WithReference`. A raw `AddContainer` would need all of that wired by hand.

  • AddProject builds a container image of the service and runs it in Docker during aspire run.
  • AddContainer can only run images built from projects in the solution.
  • WithDataVolume keeps the container itself running between AppHost runs.
  • AddExecutable runs any file name you pass, wherever it sits on disk.
  • ContainerLifetime.Persistent is the default lifetime for database containers.