Getting started

Stunts creates stunts: objects that implement an interface, derive from a class or stand in for a delegate, and send every call through a pipeline of behaviors you configure in code. It's the proxy pattern plus a chain of responsibility, with the proxies written by a Roslyn source generator at compile time.

Stunts is a low-level library: it provides the building blocks that higher-level APIs, such as mocking libraries, are made of.

Install

dotnet add package Stunts
<ItemGroup>
  <PackageReference Include="Stunts" Version="*" />
</ItemGroup>
<!-- Directory.Packages.props -->
<ItemGroup>
  <PackageVersion Include="Stunts" Version="..." />
</ItemGroup>

<!-- the project -->
<ItemGroup>
  <PackageReference Include="Stunts" />
</ItemGroup>

The package adds the runtime, the source generator, the analyzers, and the Stunt class you call to create stunts. Stunt is compiled into your project (from the Stunt.cs or Stunt.vb the package ships), which is how the generator knows which stunts your code asks for.

Compile-time stunts need C# 9 or later. Visual Basic projects use run-time proxies instead: see Compile time and run time.

Your first stunt

Take an interface:

public interface ICalculator
{
    int Add(int x, int y);
}

Stunt.For<T> creates a stunt and returns a reference to configure it. ToObject() gives you the stunt itself:

var stunt = Stunt.For<ICalculator>();
ICalculator calc = stunt.ToObject();

stunt.AddBehavior((call, next) =>
    call.CreateValueReturn(call.Arguments.Get<int>("x") + call.Arguments.Get<int>("y")));

Console.WriteLine(calc.Add(2, 3)); // 5

The behavior receives the call (IMethodInvocation: the member, its arguments, the target) and the next behavior. It ends the call with CreateValueReturn, so nothing after it runs.

A call that no behavior answers reaches the end of the pipeline. For a class member with a body, that runs the body. For an interface or abstract member, it throws NotImplementedException. Add a DefaultValueBehavior last to answer every call with a default value instead:

ICalculator calc = Stunt.For<ICalculator>()
    .AddBehavior(new DefaultValueBehavior())
    .ToObject();

calc.Add(2, 3); // 0

The packages

Package What it adds
Stunts The runtime, the Stunt factory API, the source generator and the analyzers.
Stunts.Extensions Observability, synchronization, data annotation and guard behaviors. See Stunts.Extensions.
Stunts.DynamicProxy Run-time proxies on Castle.Core, for Visual Basic and projects that can't use compile-time stunts.
ManualStunts The behavior pipeline alone, for proxies you write by hand.

Next