Behavior pipeline

Every call to a stunt becomes an IMethodInvocation that goes through the stunt's behaviors, in order. Each behavior that applies to the call can:

  • end it with a value, out and ref values, or an exception;
  • change the arguments and call the next behavior;
  • call the next behavior and look at, or replace, what it returns.

The first behavior runs outermost. When the last one calls next, the call reaches the target: the member's body for a class member that has one, the implementation passed to a delegate stunt, and a NotImplementedException otherwise.

Adding behaviors

AddBehavior appends a behavior and InsertBehavior puts it at an index. Both are extension methods on IStunt, which StuntReference<T>, StuntBuilder and every stunt implement, and both return what they were called on:

var stunt = Stunt.For<ICalculator>()
    .AddBehavior(new RecordingBehavior())
    .AddBehavior(new DefaultValueBehavior());

stunt.InsertBehavior(0, (call, next) => next(call, next), name: "first");

AddBehavior and InsertBehavior overloads

Anonymous behaviors

A lambda is a behavior. The optional appliesTo limits the calls it sees, and name shows up in the debugger:

stunt.AddBehavior(
    (call, next) => call.CreateValueReturn(42),
    appliesTo: call => call.MethodBase.Name == nameof(ICalculator.Add) && call.Arguments.Count == 2,
    name: "Add returns 42");

A behavior that doesn't apply is skipped: the call goes to the next one.

Reusable behaviors

Implement IStuntBehavior for a behavior you reuse or that keeps state:

public interface IStuntBehavior
{
    bool AppliesTo(IMethodInvocation invocation);
    IMethodReturn Execute(IMethodInvocation invocation, ExecuteHandler next);
}
public class TraceBehavior : IStuntBehavior
{
    public bool AppliesTo(IMethodInvocation invocation) => true;

    public IMethodReturn Execute(IMethodInvocation invocation, ExecuteHandler next)
    {
        Console.WriteLine($"-> {invocation}");
        var result = next(invocation, next);
        Console.WriteLine($"<- {result}");
        return result;
    }
}

The invocation

Member What it is
MethodBase The member called: a method, a property or event accessor, or a constructor.
Arguments The arguments, by name or position: Get<T>, GetNullable<T>, Set.
Target The stunt that received the call.
Context A dictionary the behaviors of one call share.
SkipBehaviors Behavior types to skip for this call (invocation.SkipBehavior<T>()).
HasImplementation Whether the member has a body to run at the end of the pipeline.

Ending a call

Call Ends the call with
invocation.CreateValueReturn(value) A return value. Overloads take the out and ref values after it.
invocation.CreateReturn(...) No return value (void), with the out and ref values.
invocation.CreateExceptionReturn(exception) An exception, thrown to the caller.
invocation.CreateInvokeReturn() The member's own body, run now.
next(invocation, next) Whatever the rest of the pipeline returns.
// bool TryAdd(ref int x, ref int y, out int z)
stunt.AddBehavior(
    (call, next) => call.CreateValueReturn(true, 1, 2, 3),
    call => call.MethodBase.Name == nameof(ICalculator.TryAdd));

Asynchronous members

A Task or ValueTask member returns its awaitable as soon as the next behavior returns, before it completes. To act on the result, call Proceed: it runs the rest of the pipeline and hands the settled outcome to a callback, after awaiting it for asynchronous members. The callback returns the outcome the caller sees, and can try again:

public class RetryOnceBehavior : IStuntBehavior
{
    public bool AppliesTo(IMethodInvocation invocation) => true;

    public IMethodReturn Execute(IMethodInvocation invocation, ExecuteHandler next)
        => invocation.Proceed(next, async (outcome, again) =>
            outcome.Exception is TimeoutException ? await again() : outcome);
}

ProceedOutcome has the Value, the Exception and the Elapsed time of the attempt. A synchronous member runs the callback before Proceed returns, so its callback must complete synchronously. A faulted task stays faulted, with its original exception. The built-in exception mapping, observability and synchronization behaviors are written this way.

Debugging

Behaviors, invocations and their results have concise debugger displays: see Debugging.