Skip to content

feat(sdk): Add C# SDK with module support - #15187

Open
pjmagee wants to merge 7 commits into
dagger:mainfrom
pjmagee:csharp/experimental
Open

pjmagee wants to merge 7 commits into
dagger:mainfrom
pjmagee:csharp/experimental

Conversation

@pjmagee

@pjmagee pjmagee commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Experimental C# SDK with module support. This supersedes #11502, which was closed as stale; the branch has since been rebased onto current main and brought up to the v1 engine.

What's in it

  • API client generated from live engine introspection: generic ID scalars, @expectedType arguments and input fields, and Relay-style node(id:) object loading.
  • Module runtime with attribute-based registration: [Object], [Interface], [Function], [Constructor], [Check], [Generate], [Up], [Name], [DefaultPath], [DefaultAddress], [Ignore], [Deprecated], [Enum]/[EnumValue].
  • Defaults and optional values from C# syntax (string? value, string value = "hello"), and async factory constructors via [Constructor] (like the Python SDK's create()).
  • Interfaces end-to-end: declaration, cross-module implementation and consumption, As{Interface}() conversions, AsInterface<T>() for dependency objects.
  • Roslyn analyzers with code fixes for compile-time validation (e.g. class name vs. module name, attribute misuse, check/generate/up contracts), configurable through .editorconfig.
  • Telemetry: W3C trace propagation so module spans join the CLI's trace.
  • Tooling: the csharp-client workspace module (.dagger/modules/csharp-client-dev) with test, lint (CSharpier), fmt, client-library generation, pack and publish. Bare csharp SDK refs resolve to github.com/dagger/dagger/sdk/csharp at the engine version, like java, php and elixir.
  • Targets .NET 10 LTS. The NuGet package (DaggerIO) is optional for modules, since the SDK is vendored with the generated client; publishing it needs a nuget.org API key owned by the Dagger team.

Checks follow the same contract as the other SDKs

A check returns void/Task and fails by throwing. To run a container as a check, await its Sync(); a non-zero exit throws. The SDK only registers withCheck(), and the engine enforces the contract (check X.y must return Void). DAGGER017 reports the same rule at compile time.

Testing

Run locally against a dev engine built from this branch (./hack/build):

  • dagger check 'csharp-client/**': test, lint, release-dry-run and the client-library staleness check pass.
  • dagger check 'markdown-lint/**' 'golangci-lint/**' pass.
  • TestCsharp: 84 passed.
  • The C# cases of the cross-SDK suites pass: TestChecks (direct/blueprint/toolchain), TestGenerators, TestUp, TestInterface and TestModule/TestContextGit (23 passed).
  • SDK unit tests: 277 passed.
  • The sample modules in pjmagee/daggerverse (dotnet, humanizer, aspnet-hello, aspnet-blazor-template, csharp-features) load and run against this branch on v1.0.0-beta.10, including dagger check, dagger generate and dagger up.

🤖 Generated with Claude Code

@pjmagee
pjmagee force-pushed the csharp/experimental branch 2 times, most recently from 84152e9 to f52322a Compare November 15, 2026 16:34
This introduces a complete C# SDK implementation for Dagger with full module
development support, at parity with the current engine.

Core Features:
- Full Dagger API client with fluent chainable interface, generated from live
  engine introspection (generic ID scalars, @expectedType arguments and
  input fields, and Relay-style node(id:) object loading)
- Module runtime with attribute-based type registration
- Support for objects, interfaces, enums, checks, and functions
- Constructor-based dependency injection with async factory methods
- State round-trips through the engine: public properties auto-expose as
  fields, object/interface values serialize as ids, enum values keep their
  registered member names, renamed members keep registration and state in
  sync
- W3C trace propagation so module spans join the CLI's trace
- The module runtime works against the client generated for whichever API
  view the module's engine version selects (e.g. FunctionCachePolicy values
  are resolved by name, whatever their casing)

Attributes:
- [Object] - Mark classes as Dagger modules
- [Interface] - Define interface types
- [Function] - Expose methods; optional overrides for properties
  (Name/Description/Deprecated)
- [Constructor] - Alternative static factory constructor (one per module)
- [Check] - Mark functions as checks for `dagger check`. Like every SDK, a
  check returns void/Task and fails by throwing; a container runs as a check
  by awaiting Sync()
- [Generate] - Mark Changeset-returning functions as generators for
  `dagger generate`
- [Up] - Mark Service-returning functions as services for `dagger up`
- [Name] - Custom parameter naming (e.g., for keyword conflicts)
- [DefaultPath] - Load contextual Directory/File/Git arguments
- [DefaultAddress] - Load an omitted Container argument from an image address
- [Ignore] - Directory ignore patterns for Directory arguments
- [Deprecated] - Deprecate functions, properties, and parameters
- [Enum]/[EnumValue] - Optional customization; plain public enums register
  automatically

Module System:
- Automatic type discovery and registration
- GraphQL schema generation from C# types
- State management with JSON serialization
- Support for Dagger types (Container, Directory, File, etc.)
- Interface support end-to-end: declaration, cross-module implementation and
  consumption via generated wrappers, As{Interface}() local conversions,
  AsInterface<T>() for dependency objects, and query-chained dynamic proxies

Developer Experience:
- Roslyn analyzers for compile-time validation with code fixes, including
  the check contract (DAGGER016/DAGGER017)
- Comprehensive examples demonstrating all features, including a standalone
  client consuming the published NuGet package
- NuGet versioning tracks the targeted engine version with a -preview suffix
  (engine v0.21.7 -> DaggerIO 0.21.7-preview)
- csharp-client workspace module (.dagger/modules/csharp-client-dev) with
  test, lint, fmt, client-library generation, pack and publish
- Bare "csharp" SDK refs resolve to github.com/dagger/dagger/sdk/csharp at
  the engine version, like java, php and elixir

Testing:
- Full integration suite (module_csharp_test.go) on the workspace/config
  module flow, plus csharp participation in the cross-SDK interface, checks
  (direct/blueprint/toolchain), generators, up, and contextual git-input
  matrices
- TestCheckFunctions covers void/Task checks, containers run as checks via
  Sync(), and the DAGGER017 rejection of Container-returning checks

Signed-off-by: pjmagee <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@pjmagee
pjmagee force-pushed the csharp/experimental branch from f52322a to b03ca8d Compare November 15, 2026 16:54
@dominik-niebuhr

dominik-niebuhr commented Nov 16, 2026 •

Copy link
Copy Markdown

Thanks for picking this up again. I packed the client from this branch (b03ca8d) and ran our integration test suites against it. Some context first, because we are a client-only user and that is a case the module tests do not cover.

Our use case

  • A .NET monorepo whose CI pipelines are Dagger modules written in TypeScript. We do not write modules in C#; what we need is the client library as a NuGet package.
  • The integration tests (xUnit v3) need real infrastructure: Postgres, TimescaleDB with our migrations applied, Kafka. Until now they used Testcontainers, which in CI meant a privileged Docker-in-Docker sidecar inside dagger check, a locked cache volume for its image store, and dependencies that never showed up in the trace.
  • We are moving the fixtures to start their dependencies as Dagger services through the client. The same fixture code has to run in two places:
    • from an IDE or plain dotnet test: the fixture starts a session itself and reaches the service through a tunnel on 127.0.0.1;
    • inside dagger check: the fixture uses the session of the check run, reaches the service by hostname and stops it on dispose.
  • Five suites, 361 tests. Besides the basic container and service calls they use Host.Tunnel with explicit ports (Kafka has to know its advertised address before it starts), Service.WithHostname, Host.Directory, WithMountedSecret, and a Postgres container that is initialised with our migration scripts in a WithExec so the result is cached.

Results

On engine v1.0.0-beta.27 all five suites pass, and our code compiled against the client without changes. Four things came up:

  1. It needs engine v1.0.0-beta.26 or later. The client is generated for the casing rename (core: rename the core API to GraphQL casing #14895), so on v1.0.0-beta.24 every Container.From fails with Unknown argument "insecureSkipTlsVerify". The package version and sdk/csharp/dagger.json still say 0.21.7, so nothing tells a user which engine it is for. A stated minimum engine version would help.

  2. Optional arguments with a default are always sent. bool insecureSkipTlsVerify = false is emitted through if (x is bool x_), which is always true for a non-nullable bool, so the argument is in every query. That is why the rename broke callers who never set it. Nullable parameters that are only sent when set would make the client tolerant of schema changes it does not use.

  3. A call that takes longer than 100 seconds fails. GraphQLClient creates its HttpClient without a timeout, so the default of 100 s applies. A WithExec(["sleep", "130"]).Sync() ends with TaskCanceledException: ... HttpClient.Timeout of 100 seconds after exactly 100 s. Setting Timeout.InfiniteTimeSpan and relying on the cancellation token would fix it.

  4. The client does not start a session. new GraphQLClient() throws without DAGGER_SESSION_PORT and DAGGER_SESSION_TOKEN, while the README says a compatible CLI is downloaded and run automatically. A test started from an IDE has no wrapper. We start dagger session ourselves, read port and token from its first output line and pass them to GraphQLClient(port, token), which works well. Either that in the SDK, as in the Go SDK's engineconn, or a README that says what is needed.

The trace propagation is valuable for us: with the published 0.21.7-preview.1 package, calls made from a test show up nested under that test in the dagger check trace, and the services a fixture starts are listed with the run. Without a forwarded trace context they were missing from both. I have not re-checked that with this branch yet, because our pipeline module is still on v1.0.0-beta.24.

Happy to test further iterations.


🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2

HttpClient cancels a request after 100 seconds by default. One GraphQL
query can wait much longer than that, for a long exec or for a service
to start, and then failed with a TaskCanceledException although the
engine was still working. The client now has no request timeout; a
caller bounds a call with its CancellationToken.

Signed-off-by: Dominik Niebuhr <[email protected]>
- Control characters in a string argument were written into the query
  unescaped, which the engine rejects. They are now escaped as \uXXXX.
- Integer arguments were formatted with the current culture.
- An error whose path contains a list index could not be deserialized,
  because the path was typed as a list of strings. The original error
  was lost behind a JsonException.
- A failed HTTP request with a body that is not JSON threw a
  JsonException. It now throws a DaggerException with the status code
  and the body.

Signed-off-by: Dominik Niebuhr <[email protected]>
@dominik-niebuhr

dominik-niebuhr commented Nov 16, 2026 •

Copy link
Copy Markdown

Follow-up to my comment above: I put fixes for the client-library side into a PR against this branch, pjmagee#14. Four commits that can be taken one by one:

  • the 100 s HttpClient timeout is gone (a 130 s exec now succeeds),
  • four small bugs in the hand-written client code (unescaped control characters in string arguments, culture-dependent integers, error paths with list indices, non-JSON error bodies),
  • the client starts a session itself when none is provided, so dotnet test and IDE test runners work without dagger run. It follows sdk/go/engineconn: _EXPERIMENTAL_DAGGER_CLI_BIN if set, else it downloads the CLI release the SDK is built for (checksum-verified, into the cache directory), and falls back to dagger from the PATH when that release is not published. That makes the README sentence about the automatic download true,
  • an example: an xUnit fixture that starts PostgreSQL as a Dagger service. It passes with plain dotnet test, under dagger run, and inside a Dagger container, where the calls of the nested client show up under the withExec in the trace.

With those commits the SDK's own test project passes on v1.0.0-beta.27 without a wrapper (73 tests).

One more observation that I did not change, because it is a packaging decision: Dagger.SDK.csproj targets only net10.0, and the package brings OpenTelemetry, OpenTelemetry.Exporter.OpenTelemetryProtocol and Microsoft.Extensions.Logging.Console plus the module runtime to every consumer. A project that only uses the client gets all of that and has to be on .NET 10. Also targeting net8.0, or splitting client and module runtime into two packages later, would widen who can use it. Not a blocker for this PR.


🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2

The client only worked under `dagger run` or inside a Dagger container,
where DAGGER_SESSION_PORT and DAGGER_SESSION_TOKEN are set. Anywhere
else it threw, so `dotnet run`, `dotnet test` and the test runner of
an IDE needed a wrapper. The READMEs already promised that a compatible
CLI is downloaded and run automatically; this adds the code for it,
following sdk/go/engineconn:

1. A provided session is used as before. A port without a token is an
   error instead of a reason to start a second session.
2. _EXPERIMENTAL_DAGGER_CLI_BIN names the CLI to run.
3. Otherwise the CLI release the SDK is built for (CliVersion) is
   downloaded from dl.dagger.io into the user's cache directory,
   checked against the published checksum, and CLIs of other versions
   are removed from the cache.
4. When that release is not published, as for a development build,
   `dagger` from the PATH is used with a warning.

The CLI is started as `dagger session` with the SDK labels and the
announced version. Like the Go SDK, the client waits up to five minutes
for the session to be reported and, on dispose or process exit, up to
five minutes for the CLI to end after its input is closed.

Client.Dag no longer caches a failed connection attempt: the next
access tries again, which matters now that connecting can involve a
download and an engine start.

CliVersion is pinned to the version in internal/version/VERSION and has
to be bumped with it, like the version files of the other SDKs.

Signed-off-by: Dominik Niebuhr <[email protected]>
An xUnit test project that starts PostgreSQL as a Dagger service from a
test fixture and reaches it through Host.tunnel. The same `dotnet test`
works on a developer machine, under `dagger run` and inside a Dagger
container.

Signed-off-by: Dominik Niebuhr <[email protected]>

@dominik-niebuhr dominik-niebuhr left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I read the parts of this PR that hook into the engine and the repository tooling, and compared them with the Java, PHP and Elixir SDKs: sdk/csharp/runtime, the csharp-client-dev module, and the changes to core/sdk and dagger.toml. I use the client and am not a maintainer, so take this as a second pair of eyes before a maintainer review.

Everything is from reading the code at b03ca8d. Where I ran something, the comment says so. The suggestions are not tested unless a comment says otherwise: I could not run the dev module against a dev engine.

Looked right to me

  • The registration in core/sdk and the entries in dagger.toml follow java-client. For people who do not use C#, the only change I see is that the name csharp is now reserved.
  • The Codegen and ModuleRuntime signatures match what the engine calls.
  • The NuGet API key in publish is passed as a secret variable and never ends up in a layer or an argument.

Most important of the inline comments

  1. The test check runs the integration tests against the CI engine instead of the dev engine.
  2. The entrypoint is dotnet run, which applies launch settings and is slow per call.
  3. The base image is a floating tag with an apt-get step on top.
  4. Initialising a module can overwrite the repository's .editorconfig.

Questions a maintainer will probably ask, not tied to a line

  • The NuGet package id DaggerIO is owned by a personal account. Who should own it once this repository publishes it? (That is also the open question in #15150.)
  • sdk/dotnet and dotnet-client-dev still exist. Does this PR replace them, and if so, when do they go?
  • When a module's source is the repository root, the repository's own Directory.Build.props, Directory.Packages.props and global.json take part in the module build. Central package management would reject the versioned PackageReferences in Dagger.SDK.props, and a global.json pinned to .NET 8 or 9 fails in the 10.0 image. Is that case meant to work?

The client-library side is covered by my earlier comment and by pjmagee#14. I am happy to send any of the points above as a PR against your branch as well.


🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2

devContainer
.withExec(["dotnet", "restore"])
.withExec(["dotnet", "build", "--no-restore"])
.withExec(["dotnet", "test", "--no-build"], experimentalPrivilegedNesting: true)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This check does not test the dev engine. The exec gets the outer session in DAGGER_SESSION_PORT/DAGGER_SESSION_TOKEN, and the C# client uses exactly those two variables. So ClientIntegrationTests talk to the engine that runs CI, while the dev engine that installClient builds and binds is never used. The check cannot catch a mismatch between the SDK and the engine of the same commit.

engine-dev/main.go describes the trap in the comment on withoutOuterSession (the variables are set when the process starts, so they have to be unset at the process boundary), and dotnet-client-dev runs its tests through dagger run. Combined:

Suggested change
.withExec(["dotnet", "test", "--no-build"], experimentalPrivilegedNesting: true)
.withExec(["env", "-u", "DAGGER_SESSION_PORT", "-u", "DAGGER_SESSION_TOKEN", "dagger", "run", "dotnet", "test", "--no-build"])

Untested: I could not run this module against a dev engine.


🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2

Comment on lines +90 to +92
let after = before
.withFile(sourcePath + "/src/introspection.json", daggerEngine(ws: self.ws).introspectionJson)
.withFile(sourcePath + "/src/Dagger.SDK/Dagger.SDK.g.cs", generatedClient)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is src/introspection.json needed in the repository? It is 1.1 MB, and I found nothing in the build that reads it: the code generator gets the schema as an argument (generatedClient above), and runtime/main.go gets it from the engine. No other SDK on main commits an introspection file. With it committed, every schema or docstring change in any PR makes this module's generated output stale.

If it can go, together with the file itself:

Suggested change
let after = before
.withFile(sourcePath + "/src/introspection.json", daggerEngine(ws: self.ws).introspectionJson)
.withFile(sourcePath + "/src/Dagger.SDK/Dagger.SDK.g.cs", generatedClient)
let after = before
.withFile(sourcePath + "/src/Dagger.SDK/Dagger.SDK.g.cs", generatedClient)

🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2

"""
Package version
"""
version: String!,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

publish accepts any version string. The comment in Dagger.SDK.csproj says the publish toolchain derives the -preview version from the engine version, but nothing here does: --version=0.21.9 would publish a stable package of an experimental SDK. java-client-dev takes the source tag and derives the version from it (release / releaseDryRun).

Two smaller things in the same function: dotnet nuget push has no --skip-duplicate, so a rerun after a partly successful push fails, and the dry run only lists the package files without looking inside them.

The secret handling itself looks right to me (withSecretVariable, quoted in the shell command).


🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2

Comment thread sdk/csharp/.gitignore
*.swp

# Code generated by Dagger.
/sdk/Dagger.SDK/introspection.json

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This entry matches nothing in this layout (it looks like it came from sdk/dotnet, where the file is ignored rather than committed). If the introspection file is dropped from generate (see my comment on main.dang), this would be the matching entry:

Suggested change
/sdk/Dagger.SDK/introspection.json
/src/introspection.json

🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2

Comment thread sdk/csharp/runtime/main.go Resolved
var parts []string
currentPart := ""
for _, r := range name {
if r == '-' || r == '_' || r == ' ' {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Names with other separators give invalid class names. Only -, _ and space split the name. A module in a directory called ci.tools becomes Ci.tools, so the template produces public class Ci.tools and Ci.tools.csproj, and the first build fails with a compiler error the user cannot relate to the name. Splitting on every character that is not a letter or digit (unicode.IsLetter / unicode.IsDigit) covers this.

Also, the doc comment on line 202 says "123test" -> "Test123", but the code below drops leading digits and returns test (lower case, because the first rune of the only part is 1). Prefixing instead of dropping would keep distinct names distinct.


🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2

}
rest := ""
if len(part) > 1 {
rest = part[1:]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This cuts a multi-byte first letter in half. firstRune is the first rune, but part[1:] skips one byte. For a part that starts with a non-ASCII letter, for example my-élan, the result is é followed by the second byte of é, which is invalid UTF-8 in the class name and the file name.

Suggested change
rest = part[1:]
rest = string([]rune(part)[1:])

Line 253 has the same pattern (result[1:]), where it only works because it runs again for every leftover byte.


🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2

}

// Build the module with specific project file
ctr = ctr.WithExec([]string{"dotnet", "build", projectFile, "-c", "Release"})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No NuGet cache. Nothing mounts a cache for ~/.nuget/packages, so this restore, and the three restores of the code generator, analyzers and code fixes above, download their packages from nuget.org again whenever their layer is not cached, which for this line is every change to the module's source. Module loads then also depend on nuget.org being reachable.

The Java runtime mounts a Maven cache volume (sdk-java-maven-m2, locked sharing) and the PHP runtime a Composer cache. The equivalent here would be a WithMountedCache("/root/.nuget/packages", dag.CacheVolume("sdk-csharp-nuget")) on base (the image runs as root). One thing to check before doing that: the entrypoint below evaluates the project again at every function call, so the cache would have to be mounted in the runtime container too, or the module published to a directory that no longer needs the packages folder.


🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we could certainly add cache for .nuget


// Set the entrypoint to run the compiled program
ctr = ctr.WithEntrypoint([]string{
"dotnet", "run", "--project", projectFile, "--no-build", "-c", "Release", "--",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dotnet run as the entrypoint. Two effects on every function call:

  • dotnet run applies the module's Properties/launchSettings.json. A profile there, which IDEs create by themselves, changes the environment of every function call in the engine.
  • It evaluates the project before starting the program. With a trivial app I measured about 0.4 to 0.7 s per start for dotnet run --no-build against about 0.04 s for dotnet App.dll (locally on macOS, not in the engine). Every function call is a fresh exec, so this is paid each time.

The small fix is the flag below (it exists in the SDK of this image, checked with dotnet run --help). The better one would be to publish the module to a fixed directory in ModuleRuntime and start the dll directly, as the Java runtime does with java -jar.

Suggested change
"dotnet", "run", "--project", projectFile, "--no-build", "-c", "Release", "--",
"dotnet", "run", "--project", projectFile, "--no-build", "--no-launch-profile", "-c", "Release", "--",

🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2

Comment thread sdk/csharp/dagger.json
@@ -0,0 +1,11 @@
{
"name": "csharp-sdk",
"engineVersion": "v0.21.7",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Java, PHP and Elixir runtime modules are on v0.21.9 on main, and so is the new csharp-client-dev module. Is v0.21.7 here intended?


🤖 Posted by Claude on behalf of Dominik · Claude Code 2.1.325 · claude-fable-5-2

pjmagee and others added 2 commits November 16, 2026 13:53
…-fixes

fix(sdk/csharp): client session start, request timeout and error handling
Co-authored-by: dominik-niebuhr <[email protected]>
Signed-off-by: Patrick Magee <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants