What Awaiten generates
Awaiten does its work at build time. For every [Container] the source generator writes a plain C# file that wires the graph, and the compiler builds it with the rest of your project. Nothing is discovered or emitted at run time.
This page walks through that file for the coffee shop of the complete example, so you can see what runs when the shop serves an order. The excerpts come from the real generated file, simplified: the global:: prefixes, the disposed checks and the guards against re-entrant builds are left out, and // … marks elided code.
The generated Root and Scope types, the public constructors of Root and the members of the interfaces they implement are the public surface you program against (see the runtime API). Everything else, such as the names of resolver methods, fields and the dispatch table, is an implementation detail that changes between versions. Do not call or reflect over it.
Two nested types
The generator adds one file named after the container, Awaiten.CoffeeShop.g.cs. It completes your static partial class CoffeeShop with two nested types: Scope, which holds the resolution logic, and Root, which derives from it.
// <auto-generated/>
static partial class CoffeeShop
{
public sealed class Root : Scope, IAwaitenRoot
{
public Root() : this(null) { }
public Root(IExternalResolver? externalResolver) : base(externalResolver) { }
public Task InitializeAsync(CancellationToken cancellationToken = default) { /* … */ }
public AwaitenResolvability GetResolvability(Type serviceType, object? key) { /* … */ }
// the singleton resolvers …
}
public class Scope : IAwaitenScope, IAwaitenExternalResolverHost,
IAwaitenResolver<Grinder>, IAwaitenResolver<MenuBoard>, IAwaitenResolver<Barista>, // …
IAwaitenAsyncResolver<EspressoMachine>, // …
{
// Resolve, TryResolve, ResolveAsync with their Type and keyed overloads,
// CreateScope, CreateScopeAsync, Dispose, DisposeAsync,
// and the resolvers of the scoped and transient services …
}
}
Rootis whatawait using CoffeeShop.Root shop = new();creates. It is the outermost scope, and it holds the singletons: theEspressoMachine, theGrinder, the milks, the syrups and the terminal.Scopeis whatshop.CreateScope()returns for each order. It holds that order'sOrder,TabandBarista, and it reaches the singletons through the root.- The
Root(IExternalResolver?)constructor takes the resolver for imported services. The coffee shop imports none. - The scope implements
IAwaitenResolver<T>for each unkeyed service without runtime arguments that it resolves synchronously andIAwaitenAsyncResolver<T>for every unkeyed service without runtime arguments, async or not, soResolve<T>()andResolveAsync<T>()take a typed path without a lookup.
One resolver per registration
Every registration gets a static resolver method, and a dependency is a direct call to the resolver of its registration. The constructor arguments are plain method calls that the compiler checks.
A singleton
The Grinder is cached on the root. The resolver returns the cached instance without a lock and builds it under a lock the first time:
internal static Grinder ResolveGrinder(Root __s)
{
if (__s._grinder is not null)
{
return __s._grinder;
}
lock (__s.__gate)
{
if (__s._grinder is null)
{
__s._grinder = new Grinder();
}
}
return __s._grinder;
}
The decorated terminal from the PaymentModule is a singleton of the same shape. Its resolver builds the decorator around the inner registration, so nothing can reach the bare CardTerminal as an IPaymentTerminal:
__s._loggingTerminal = new LoggingTerminal(Root.ResolveCardTerminal(__s.__root));
The pre-built MenuBoard has no cache of its own. Its resolver returns the Instance member you named, and the root never disposes it:
internal static MenuBoard ResolveMenuBoard(Root __s) => Menu;
A scoped service
The Tab is cached on the scope that resolves it, so each order gets its own. Because the Tab is disposable, its resolver also adds it to the scope's list of disposables, which the scope tears down in reverse order when the order is done:
internal static Tab ResolveTab(Scope __s)
{
if (__s._tab is not null)
{
return __s._tab;
}
lock (__s.__gate)
{
if (__s._tab is null)
{
__s._tab = new Tab(ResolveOrder(__s));
(__s.__disposables ??= new List<object>()).Add(__s._tab);
}
}
return __s._tab;
}
The barista and its relationships
The Barista is scoped too. Its constructor call shows how each relationship and collection shape turns into plain code:
__s._barista = new Barista(
ResolveTab(__s),
new Func<string, Task<Cup>>((a0) => ResolveCupAsync(__s, a0, default)),
new Dictionary<string, IMilk> { ["Oat"] = Root.ResolveOatMilk(__s.__root), ["Whole"] = Root.ResolveWholeMilk(__s.__root) },
new ISyrup[] { Root.ResolveVanillaSyrup(__s.__root), Root.ResolveCaramelSyrup(__s.__root) },
Root.ResolveLoggingTerminal(__s.__root));
- The
Func<string, Task<Cup>>is a lambda over the cup's resolver. The runtime argumentsizearrives asa0. - The keyed dictionary of milks is a dictionary literal with one entry per key.
- The collection of syrups is an array in declaration order.
A transient built by a factory
Each call of the barista's Func builds a new Cup through the MakeCup factory. The cup needs the async EspressoMachine, so its resolver is asynchronous and awaits the machine before it calls the factory:
internal static async Task<Cup> ResolveCupAsync(Scope __s, string a0, CancellationToken cancellationToken)
{
Cup created = MakeCup(
await Root.ResolveEspressoMachineAsync(__s.__root, cancellationToken).ConfigureAwait(false),
Root.ResolveGrinder(__s.__root),
a0);
return created;
}
Async initialization
The EspressoMachine matches the [AsyncInitializer<IWarmUp>] convention, so it gets an asynchronous resolver instead. It caches the Task that builds and warms the machine, so WarmUpAsync runs once even when several callers resolve it at the same time. A task that failed or was canceled is not kept, so the next call tries again.
internal static Task<EspressoMachine> ResolveEspressoMachineAsync(Root __s, CancellationToken cancellationToken)
{
Task<EspressoMachine>? __cached = __s._espressoMachineAsyncTask;
if (__cached is not null && !__cached.IsFaulted && !__cached.IsCanceled)
{
return __cached;
}
lock (__s.__gate)
{
// start CreateEspressoMachineAsync once and store its task in _espressoMachineAsyncTask …
}
async Task<EspressoMachine> CreateEspressoMachineAsync()
{
EspressoMachine created = new EspressoMachine();
await ((IWarmUp)created).WarmUpAsync(cancellationToken).ConfigureAwait(false);
return created;
}
}
shop.InitializeAsync() at startup awaits the asynchronous resolver of every async singleton, in dependency order. In the coffee shop that is the machine alone:
public Task InitializeAsync(CancellationToken cancellationToken = default)
{
return Core();
async Task Core()
{
await ResolveEspressoMachineAsync(this, cancellationToken).ConfigureAwait(false);
}
}
In the strict default, an async-initialized service has no synchronous resolver at all, so no synchronous path can hand out a cold machine. That is why the barista takes its cups through a Task. Under AsyncSafety.SyncAfterInit, a synchronous resolver would wait for the asynchronous one. See Async initialization.
How resolve by type finds a service
order.Resolve<Barista>() takes the typed path through IAwaitenResolver<Barista>. Resolve(Type), TryResolve(Type, …) and the shapes without a typed implementation, such as Func<Grinder>, look the type up in a static table that the Scope builds once. Each entry maps a Type to the resolver that produces it, and the table also holds the shapes the container synthesizes over each service:
static Scope()
{
__Bucket[] __entries =
{
new __Bucket(typeof(Grinder), static __s => Root.ResolveGrinder(__s.__root), false),
// …
new __Bucket(typeof(Tab), static __s => ResolveTab(__s), false),
new __Bucket(typeof(Barista), static __s => ResolveBarista(__s), false),
// …
new __Bucket(typeof(IPaymentTerminal), static __s => Root.ResolveLoggingTerminal(__s.__root), false),
new __Bucket(typeof(Func<Grinder>), __R0, false),
// …
new __Bucket(typeof(Func<string, Task<Cup>>), __R33, false),
// …
};
__buckets = __BuildBuckets(__entries);
}
Each shape that has no resolver of its own, such as Func<Grinder> or the Func the barista takes, gets a small helper (__R0, __R33) that the table points to, so the table and its helpers grow with the registrations. The lookup hashes the type into a bucket of a static array and compares the few Type instances in that bucket by identity, so finding a service costs a hash and a short scan, not a walk over every registration, and it needs no reflection.
Resolve(Type) throws an InvalidOperationException when the table has no entry. For a service the container has but withholds from that call, such as the EspressoMachine on a synchronous Resolve, the message names the fix.
A container with errors
When the container has an error, the generator emits no wiring. The file then contains only a Root that implements IAwaitenRoot and throws on use, so code that uses only the Root still compiles and the build reports the actual AWT diagnostics instead of follow-up errors about a missing type:
public object Resolve(Type serviceType) => throw new InvalidOperationException(
"Awaiten: container 'CoffeeShop' has registration errors; see the build diagnostics (AWT1xx).");
TryResolve on it returns false, and Dispose does nothing. This is what you get at run time when an error is suppressed or lowered so that the build passes, as the Diagnostics page explains.
See the generated code
In Visual Studio, open the project in Solution Explorer and expand Dependencies, Analyzers, Awaiten.SourceGenerators and Awaiten.SourceGenerators.AwaitenGenerator. Go to Definition on CoffeeShop.Root opens the file too. Rider lists the files of source generators under the project's dependencies as well.
To keep the files on disk, for a code review or a diff between versions, set EmitCompilerGeneratedFiles in the project file:
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
</PropertyGroup>
The compiler then writes them below the intermediate output, to obj/<Configuration>/<TargetFramework>/generated/Awaiten.SourceGenerators/Awaiten.SourceGenerators.AwaitenGenerator/. Set CompilerGeneratedFilesOutputPath to choose another folder. When that folder is inside the project, remove its files from compilation, because the generator already adds them:
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
<ItemGroup>
<Compile Remove="$(CompilerGeneratedFilesOutputPath)/**/*.cs" />
</ItemGroup>
What this gives you
- No reflection. The generated code constructs with
new, calls the factories and hooks you named, and looks types up by identity withtypeof. It never scans assemblies or creates types at run time. A scan is read from the compilation at build time. - Plain C#. You can read, step through and set breakpoints in the generated file like in your own code.
- Native AOT and trimming. The generated code and the
Awaitenlibrary contain no reflection-based activation. The MS.DI bridge constructs no generic types at run time and supports native AOT as well. - Every target framework. The same file compiles for every framework Awaiten supports, .NET Framework 4.8 included, with the language version the requirements name.
A module in another assembly can generate code too: a public, partial module emits the factories and handles a container in that other assembly needs. See Shipping modules from a library.
Where to go next
- Runtime API for the public surface of
RootandScope. - Scopes for how the root and its child scopes relate.
- Diagnostics for the checks that run while the file is generated.