中文 | English
Rougamo is a static code weaving AOP component. Commonly used AOP components include Castle, Autofac, and AspectCore. Unlike these components, which typically implement AOP through dynamic proxy and IoC mechanisms at runtime, Rougamo achieves AOP by directly modifying the target method's IL code during compilation. Rougamo supports all types of methods, including synchronous/asynchronous methods, static/instance methods, constructors, and properties.
Rougamo, a type of traditional Chinese street food, is somewhat similar to a hamburger, as both involve meat being sandwiched between bread. Every time I mention AOP, I think of Rougamo, because AOP is just like Rougamo, do aspects around the mehod.
-
Advantages:
- Shorter Application Startup Time, Static weaving occurs at compile time, whereas dynamic proxies are set up at application startup.
- Support for All Methods, Rougamo supports all methods, including constructors, properties, and static methods. Dynamic proxies often only handle instance methods due to their reliance on IoC.
- Independent from Other Components, Rougamo does not require initialization and is easy and quick to use. Dynamic AOP relies on IoC components, which often need initialization at application startup and vary between different IoC components. Rougamo does not require initialization; you just define the aspect type and apply it.
-
Disadvantages: Larger Assembly Size, Since Rougamo is a compile-time AOP, it weaves additional code into the assembly at compile time, which increases the assembly size. However, this overhead is generally minimal and can be evaluated in your project through configuration options.
As an AOP component, Rougamo's primary function is to execute additional operations at key lifecycle points of a method. Rougamo supports four lifecycle points (or Join Points):
- Before method execution;
- After method execution successfully;
- After method throws an exception;
- When the method exits (regardless of whether it was successful or threw an exception, similar to
try..finally
).
Here's a simple example demonstrating how lifecycle points are expressed in code:
// Define a type inheriting from MoAttribute
public class TestAttribute : MoAttribute
{
public override void OnEntry(MethodContext context)
{
// OnEntry corresponds to before method execution
}
public override void OnException(MethodContext context)
{
// OnException corresponds to after method throws an exception
}
public override void OnSuccess(MethodContext context)
{
// OnSuccess corresponds to after method execution successfully
}
public override void OnExit(MethodContext context)
{
// OnExit corresponds to when method exits
}
}
At each lifecycle point, in addition to performing operations like logging, measuring method execution time, and APM instrumentation that don't affect method execution, you can also:
- Modify method parameters
- Intercept method execution
- Modify method return values
- Handle method exceptions
- Retry method execution
The simplest and most direct way is to apply the defined Attribute
directly to methods. This can include synchronous and asynchronous methods, instance methods and static methods, properties and property getters/setters, as well as instance and static constructors:
class Abc
{
[Test]
static Abc() { }
[Test]
public Abc() { }
[Test]
public int X { get; set; }
public static Y
{
[Test]
get;
[Test]
set;
}
[Test]
public void M() { }
[Test]
public static async ValueTask MAsync() => await Task.Yield();
}
Applying attributes directly to methods is straightforward, but for common AOP types, adding the attribute to every method can be cumbersome. Rougamo also provides several bulk application methods:
- Class or assembly-level attributes
- Low-intrusive implementation of the empty interface IRougamo
- Specify an attribute as a proxy attribute and apply it to methods with the proxy attribute
- Non-intrusive configurative weaving method
When applying attributes in bulk, such as applying TestAttribute
to a class, you typically don’t want every method in the class to receive TestAttribute
. Instead, you may want to select methods that meet specific criteria. Rougamo offers two methods for method selection:
- Coarse-grained method feature matching, which allows specifying static, instance, public, private, property, constructor methods, etc.
- AspectJ-style class expressions, which provide AspectJ-like expressions for finer-grained matching, such as method names, return types, parameter types, etc.
In modern development, asynchronous programming has become quite common. In the previous example, the method lifecycle nodes correspond to synchronous methods. If you need to perform asynchronous operations, you would have to manually block asynchronous operations to wait for the results, which can lead to resource wastage and performance loss. Rougamo provides asynchronous aspects in addition to synchronous aspects to better support asynchronous operations:
// Define a type that inherits from AsyncMoAttribute
public class TestAttribute : AsyncMoAttribute
{
public override async ValueTask OnEntryAsync(MethodContext context) { }
public override async ValueTask OnExceptionAsync(MethodContext context) { }
public override async ValueTask OnSuccessAsync(MethodContext context) { }
public override async ValueTask OnExitAsync(MethodContext context) { }
}
However, if asynchronous operations are not needed, it's still recommended to use synchronous aspects. For more information on asynchronous aspects, you can refer to Asynchronous Aspects.
Rougamo is a method-level AOP component. When applying Rougamo to methods, it instantiates related objects each time the method is called, which adds a burden to garbage collection (GC). Although this overhead is usually minimal and often negligible, Rougamo addresses performance impact by providing various optimization strategies:
-
Partial Weaving: If you only want to record a call log before method execution and do not need other lifecycle nodes or exception handling, you can use partial weaving to include only the required functionalities. This reduces the actual IL code woven and minimizes the number of instructions executed at runtime.
-
Structs: One difference between classes and structs is that classes are allocated on the heap, while structs are allocated on the stack. Using structs can allocate some Rougamo types on the stack, reducing GC pressure.
-
Slimming MethodContext:
MethodContext
holds contextual information about the current method. This information requires additional objects and involves boxing and unboxing operations, such as for method parameters and return values. If you do not need this information, slimming downMethodContext
can achieve certain optimization effects. -
Forced Synchronization: As discussed in Asynchronous Aspects, asynchronous aspects use
ValueTask
to optimize synchronous execution but still incur additional overhead. If asynchronous operations are not required, forcing synchronous aspects can avoid the extra costs of asynchronous aspects. -
Custom Aspect Type Lifecycle, structs can avoid the creation of reference types, but they also have many limitations themselves, such as being unable to inherit from a parent class to reuse logic, unable to inherit from Attribute which results in an inability to specify parameters when applying aspect types (Attributes can specify constructor and property parameters when applied [Xyz(123, V = "abc")]). A way to balance usability and performance is through custom declaration cycles.
- Configuration Options
- Using IoC in Rougamo
- Special Note on async void
- Custom Execution Order When Using Multiple Rougamo Types
- Specifying Rougamo Built-in Attributes When Using Attributes
- Special Parameters or Return Value Types (ref struct)
- Considerations for Developing Middleware with Rougamo
- Overview of Functional Support for Different Method Types