Skip to content

Repository files navigation

Stunts

Stunts

Version Downloads EULA OSS Discord Chat

Open Source Maintenance Fee

To ensure the long-term sustainability of this project, users of this package who generate revenue must pay an Open Source Maintenance Fee. While the source code is freely available under the terms of the License, this package and other aspects of the project require adherence to the Maintenance Fee.

To pay the Maintenance Fee, become a Sponsor at the proper OSMF tier. A single fee covers all of Devlooped packages.

A modern interception library that runs everywhere, even where run-time code generation (Reflection.Emit) is forbidden or limitted (i.e. physical iOS devices and game consoles), through compile-time code generation.

The Stunts name was inspired by the Test Double naming in the mock objects literature, which in turn comes from the Stunt Double concept from film making. This project allows your objects to pull arbitrary stunts based on your instructions/choreography 😉.

Stunts essentially implements the proxy pattern and adds the capability of configuring those proxies via code using what we call a behavior pipeline.

NOTE: Stunts provides a fairly low-level API with just the essential building blocks on top of which higher-level APIs can be built, such as the upcoming Moq vNext API.

Requirements

Stunts is a .NET Standard 2.0 library and runs on any runtime that supports that.

Compile-time proxy generation leverages Roslyn source generators and therefore requires C# 9.0, which at this time is included in Visual Studio 16.8 (preview or later) and the .NET 5.0 SDK (RC or later). Compile-time generated proxies support the broadest possible run-time platforms since they don't require any Reflection.Emit, and also don't pay that performance cost either.

Whenever compile-time proxy generation is not available (i.e. Visual Basic or C# versions before 9.0), install the Stunts.DynamicProxy package instead, which leverages Castle DynamicProxy to provide the run-time code generation.

The client API for configuring proxy behaviors in either case is exactly the same.

NOTE: even though generated proxies are the main usage for Stunts, the API was designed so that you can also consume the behavior pipeline easily from hand-coded proxies too.

Usage

ICalculator calc = Stunt.Of<ICalculator>();

calc.AddBehavior((invocation, next) => ...);

AddBehavior/InsertBehavior overloads allow granular control of the stunt's behavior pipeline, which is basically a chain of responsibility that invokes all configured behaviors that apply to the current invocation. Individual behaviors can determine whether to short-circuit the call or call the next behavior in the chain.

Stunts Overloads

Behaviors can also dynamically determine whether they apply to a given invocation by providing the optional appliesTo argument. In addition to the delegate-based overloads (called anonymous behaviors), you can also create behaviors by implementing the IStuntBehavior interface:

public interface IStuntBehavior
{
    bool AppliesTo(IMethodInvocation invocation);
    IMethodReturn Execute(IMethodInvocation invocation, ExecuteHandler next);
}

Common Behaviors

Some commonly used behaviors that are generally useful are provided in the library and can be added to stunts as needed:

  • DefaultValueBehavior: sets default values for method return and out arguments. In addition to the built-in supported default values, additional default value factories can be registered for any type.

  • DefaultEqualityBehavior: implements the Object.Equals and Object.GetHashCode members just like System.Object implements them.

  • RecordingBehavior: simple behavior that keeps track of all invocations, for troubleshooting or reporting.

Customizing Stunt Creation

If you want to centrally configure all your stunts, the easiest way is to simply provide your own factory method (i.e. Stub.Of<T>), which in turn calls the Stunt.Of<T> provided. For example:

    public static class Stub
    {
        [StuntGenerator]
        public static T Of<T>() => Stunt.Of<T>()
            .AddBehavior(new RecordingBehavior())
            .AddBehavior(new DefaultEqualityBehavior())
            .AddBehavior(new DefaultValueBehavior());
    }

The [StuntGenerator] attribute is required if you want to leverage the built-in compile-time code generation, since that signals to the source generator that calls to your API end up creating a stunt at run-time and therefore a generated type will be needed for it during compile-time. You can actually explore how this very same behavior is implemented in the built-in Stunts API, which is provided as content files (Stunt.cs and Stunt.vb):

[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));

As you can see, the Stunts API itself uses the same extensibility mechanism that your own custom factory methods can use.

Static vs Dynamic Stunts

By default, Stunts generates proxies at compile-time (powered by Roslyn source generators), which is only supported when building C# 9.0+ projects.

Whenever compile-time stunts are not supported (or not wanted), install the Stunts.DynamicProxy package, which switches the project to run-time proxies based on Castle.Core:

<ItemGroup>
    <PackageReference Include="Stunts.DynamicProxy" Version="..." />
</ItemGroup>

The package sets EnableCompileTimeStunts=false for you. Projects that can't use compile-time stunts and don't reference Stunts.DynamicProxy get a build warning (ST011).

Debugging Optimizations

There is nothing more frustrating than a proxy/stunt you have carefully configured that doesn't behave the way you expect it to. In order to make this a less frustrating experience, Stunts is carefully optimized for debugger display and inspection, so that it's clear what behaviors are configured, and invocations and results are displayed clearly and concisely. Here's the debugging display of the RecordingBehavior that just keeps track of invocations and their return values for example:

debugging display

And here's the invocation debugger display from an anonymous behavior:

behavior debugging

Samples

The samples folder in the repository contains a few interesting examples of how Stunts can be used to implement some fancy use cases. For example:

  • Forwarding calls to matching interface methods/properties (by signature) to a static class. The example uses this to wrap calls to System.Console via an IConsole interface.

  • Forwarding calls to a target object using the DLR (that backs the dynamic keyword in C#) API for high-performance late binding.

  • Custom Stub.Of<T> factory that creates stunts that have common behaviors configured automatically.

  • Custom stunt factory method that adds an int return value randomizer.

  • Configuring the built-in DefaultValueBehavior so that every time a string property is retrieved, it gets a random lorem ipsum value.

  • Logging all calls to a stunt to the Xunit output helper.

Sponsors

Clarius Org MFB Technologies, Inc. SandRock DRIVE.NET, Inc. Keith Pickford Thomas Bolon Reuben Swartz Jacob Foshee Eric Johnson Jonathan Ken Bonny Simon Cropp agileworks-eu Zheyu Shen Vezel ChilliCream 4OTC domischell Adrian Alonso torutek Ryan McCaffery Seika Logiciel Andrew Grant eska-gmbh Geodata AS

Sponsor this project

Learn more about GitHub Sponsors

About

A modern compile-time generated interception/proxy library

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

141 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Used by

Contributors

Languages