All Projects → devlooped → avatar

devlooped / avatar

Licence: MIT License
A modern compile-time generated interception/proxy library

Programming Languages

C#
18002 projects

Projects that are alternatives of or similar to avatar

AutoInterface
C# interface-to-member source generator
Stars: ✭ 47 (-41.25%)
Mutual labels:  csharp-sourcegenerator
JsonSrcGen
Json library that uses .NET 5 Source Generators
Stars: ✭ 140 (+75%)
Mutual labels:  csharp-sourcegenerator
GraphQL.Tools
GraphQL.Tools is a GraphQL to C# compiler (code-generator) which turns your GraphQL schema into a set of C# classes, interfaces, and enums.
Stars: ✭ 49 (-38.75%)
Mutual labels:  csharp-sourcegenerator
Vogen
A semi-opinionated library which is a source generator and a code analyser. It Source generates Value Objects
Stars: ✭ 240 (+200%)
Mutual labels:  csharp-sourcegenerator
dotvariant
A type-safe and space-efficient sum type for C# (comparable to discriminated unions in C or C++)
Stars: ✭ 52 (-35%)
Mutual labels:  csharp-sourcegenerator
EmbeddingResourceCSharp
Embed resource files more C# programmer friendly!
Stars: ✭ 22 (-72.5%)
Mutual labels:  csharp-sourcegenerator
DpdtInject
Highly efficient compile-time general purpose DI container based on C# source generators.
Stars: ✭ 25 (-68.75%)
Mutual labels:  csharp-sourcegenerator
GitBuildInfo.SourceGenerator
Source Generator for dumping the git branch information, commit hash, and if the working tree is dirty or clean on projects that install this and applies them as an assembly level attribute.
Stars: ✭ 15 (-81.25%)
Mutual labels:  csharp-sourcegenerator
Immutype
Immutability is easy!
Stars: ✭ 26 (-67.5%)
Mutual labels:  csharp-sourcegenerator
Plastic
This project provides encapsulation of things like Domain, Application Rules, Business Rules or Business Logic in Application.
Stars: ✭ 30 (-62.5%)
Mutual labels:  csharp-sourcegenerator
Uragano
Uragano, A simple, high performance RPC library. Support load balancing, circuit breaker, fallback, caching, intercepting.
Stars: ✭ 28 (-65%)
Mutual labels:  dynamicproxy
ThisAssembly
Exposes project and assembly level information as constants in the ThisAssembly class using source generators powered by Roslyn.
Stars: ✭ 209 (+161.25%)
Mutual labels:  csharp-sourcegenerator
GodotOnReady
A C# Source Generator that adds convenient onready-like features to your C# scripts in Godot Mono without any reflection.
Stars: ✭ 73 (-8.75%)
Mutual labels:  csharp-sourcegenerator
spreadcheetah
SpreadCheetah is a high-performance .NET library for generating spreadsheet (Microsoft Excel XLSX) files.
Stars: ✭ 107 (+33.75%)
Mutual labels:  csharp-sourcegenerator
StructPacker
Low-level, lightweight and performance-focused serializer for C# struct types that uses Source Generators technology.
Stars: ✭ 42 (-47.5%)
Mutual labels:  csharp-sourcegenerator
proxybuilder
www.proxybuilder.org
Stars: ✭ 19 (-76.25%)
Mutual labels:  dynamicproxy
WinFormsComInterop
ComWrappers required to run NativeAOT and WinForms
Stars: ✭ 54 (-32.5%)
Mutual labels:  csharp-sourcegenerator
StringLiteralGenerator
C# Source Generator for UTF-8 binary literal
Stars: ✭ 109 (+36.25%)
Mutual labels:  csharp-sourcegenerator
TypedSignalR.Client
C# Source Generator to Create Strongly Typed SignalR Client.
Stars: ✭ 16 (-80%)
Mutual labels:  csharp-sourcegenerator
Generator.Equals
A source code generator for automatically implementing IEquatable<T> using only attributes.
Stars: ✭ 49 (-38.75%)
Mutual labels:  csharp-sourcegenerator

Icon Avatar

Avatar is a modern interception library which implements the proxy pattern and runs everywhere, even where run-time code generation (Reflection.Emit) is forbidden or limitted, like physical iOS devices and game consoles, through compile-time code generation. The proxy behavior is configured in code using what we call a behavior pipeline.

Avatars blend in with the Na'vi seamlessly, and you can control their behavior precisely by 'driving' them through a psionic link. Just like a proxy, with behavior driven through code.

Avatar Overloads

Version Downloads License Discord Chat GitHub

CI Version GH CI Status

NOTE: Avatar 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

Avatar 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, a fallback generation strategy is used 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 is the main usage for Avatar, the API was designed so that you can also consume the behavior pipeline easily from hand-coded proxies too.

Usage

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

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

AddBehavior/InsertBehavior overloads allow granular control of the avatar'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.

Avatar 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 IAvatarBehavior interface:

public interface IAvatarBehavior
{
    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 avatars 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 Avatar Creation

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

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

The [AvatarGenerator] 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 an avatar 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 Avatar API which is provided as a content file:

avatar API source

The Avatar.cs contains, for example:

[AvatarGenerator]
public static T Of<T>(params object[] constructorArgs) => Create<T>(constructorArgs);

[AvatarGenerator]
public static T Of<T, T1>(params object[] constructorArgs) => Create<T>(constructorArgs, typeof(T1));

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

Static vs Dynamic Avatars

Depending on the project and platform, Avatars will automatically choose whether to use run-time proxies or compile-time ones (powered by Roslyn source generators). The latter are only supported when building C# 9.0+ projects.

You can opt out of the static avatars by setting EnableCompiledAvatars=false in your project file:

<PropertyGroup>
    <EnableCompiledAvatars>false</EnableCompiledAvatars>
</PropertyGroup>

This will switch the project to run-time proxies based on Castle.Core.

Debugging Optimizations

There is nothing more frustrating than a proxy you have carefully configured that doesn't behave the way you expect it to. In order to make this a less frustrating experience, avatars are 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 Avatar 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 avatars that have common behaviors configured automatically.

  • Custom avatar 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 an avatar to the Xunit output helper.

Sponsors

sponsors  by @clarius sponsors

get mentioned here too!

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].