NexusAop is a powerful and flexible library for reflection and aspect-oriented programming (AOP) in .NET 5.0. This library enables developers to easily apply cross-cutting concerns to their applications by utilizing custom attributes. With NexusAop, you can interrupt method executions, perform specific actions, and retrieve results seamlessly.
$ dotnet add package NexusAOPNexusAop is a powerful and flexible library for reflection and aspect-oriented programming (AOP) in .NET 5.0. This library enables developers to easily apply cross-cutting concerns to their applications by utilizing custom attributes. With NexusAop, you can interrupt method executions, perform specific actions, and retrieve results seamlessly.
To start using NexusAop in your .NET 5.0 project, follow these simple steps:
dotnet add package NexusAop
2. Service Implementation:
serviceCollection.AddSingletonWithCustomAop<ITestService, TestService>();
Decorate your methods with custom attributes to define the desired cross-cutting concerns.
[CustomAspect]
public async Task<int> MyMethodAsync()
{
// Your method implementation
}
Use the provided methods such as NextAsync() and ExecuteAndGetResultAsync() within your custom aspects to influence the method execution flow.
public class CustomAspectAttribute : NexusAopAttribute
{
public override async Task ExecuteAsync(NexusAopContext context)
{
// Perform actions before the method execution
// Proceed with the execution of the target method
var result = await context.NextAsync();
// User-defined logic after the target method
// Get the result if you needed
var setResult= await context.ExecuteAndGetResultAsync();
return result;
}
}
Build your project, and NexusAop will seamlessly weave the specified aspects into your methods during runtime.
public class CacheMethodAttribute : NexusAopAttribute
{
public CacheMethodAttribute(
int ttlAsSecond)
{
Ttl = TimeSpan.FromSeconds(ttlAsSecond);
}
public CacheMethodAttribute()
{
Ttl = null;
}
public TimeSpan? Ttl { get; set; }
public override async Task ExecuteAsync(NexusAopContext context)
{
if (!CheckMethodCacheable(context.TargetMethod))
{
return;
}
var cacheKey = GetCacheKey(context.TargetMethod, context.TargetMethodsArgs);
var result = GetResult(cacheKey);
if (result != null)
{
context.Result= result;
return;
}
result = await context.ExecuteAndGetResultAsync();
await SetCacheAsync(context.TargetMethod, context.TargetMethodsArgs,result);
}
// ...
// see CacheMethodAttribute.cs in /Samples/Cache for other logics
// ...
}
Contributions are welcome! If you encounter any issues or have suggestions for improvements, please feel free to create an issue or submit a pull request.
This project is licensed under the BSD 3-Clause License.