The source generator finds the stunts your code needs by looking at calls to methods marked
[StuntGenerator]: their generic type arguments are the stunt's base type and interfaces. The
Stunt class is just such a set of methods, compiled into your project:
[StuntGenerator]
public static T Of<T>(params object[] constructorArgs) => Create<T>(constructorArgs);
[StuntGenerator]
public static T Of<T, T1>(params object[] constructorArgs) => Create<T>(constructorArgs, typeof(T1));
Your own API works the same way.
Mark a factory that ends up creating stunts with [StuntGenerator], and the generator writes the
stunts its callers ask for:
public static class Stub
{
[StuntGenerator]
public static T Of<T>() => Stunt.For<T>()
.AddBehavior(new RecordingBehavior())
.AddBehavior(new DefaultEqualityBehavior())
.AddBehavior(new DefaultValueBehavior())
.ToObject();
}
ICalculator calc = Stub.Of<ICalculator>();
The attribute is needed for compile-time stunts only: with run-time proxies any factory works.
A generic method that builds stunt types from its own type parameters is a wrapper, and must be
marked too (ST016, with a code fix that adds the attribute):
[StuntGenerator]
static IDictionary<string, T> Create<T>() => Stunt.Of<IDictionary<string, T>>();
IDictionary<string, int> dictionary = Create<int>();
The generator follows wrappers, up to 8 levels and across referenced assemblies, and generates the
closed stunt each call site needs, here IDictionary<string, int>. Every generated stunt is a closed
type, so only the combinations your code uses are generated.
A wrapper:
ST017): make them type parameters of the method;ST018), since its callers couldn't know which implementation runs;ST019).Local functions can be wrappers.
A stunt type no call site reveals, such as one built from a run-time Type, is registered with an
assembly attribute anywhere in the project:
[assembly: Stunt<IDictionary<string, DateTime>, IDisposable>]
Asking for a stunt that was not generated throws a NotSupportedException whose message has the
exact attribute to add.