Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

fasetto/SharpAspect

Repository files navigation

Getting Started

Nuget
dotnet add package SharpAspect

SharpAspect is an AOP (Aspect-Oriented Programming) package for .Net
It depends on Castle.Core DynamicProxy. Currently only supports method and property interception.

Take advantage of run-time interception for your next project.

Check the wiki page for more samples and documentation.

Defining & Mapping your Interceptors

Method Interception

public class LogAttribute: MethodInterceptorAttribute
{
}
// You must specify the attribute for the interceptor.
[InterceptFor(typeof(LogAttribute))]
public class LogInterceptor: MethodInterceptor
{
 private readonly Logger logger;
 // The Logger dependency will be resolved using Microsoft's DI container
 public LogInterceptor(Logger logger)
 {
 this.logger = logger;
 }
 // MethodInterceptor class provides OnBefore, OnAfter and OnError methods.
 // You can override these methods to seperate the logic you don't want in your actual method.
 public override Task OnBefore(IInvocation invocation)
 {
 logger.LogInfo($"[Log] Executing method: {invocation.TargetType.FullName}.{invocation.Method.Name}");
 return Task.FromResult(Task.CompletedTask);
 }
}

Simple logger.

public class Logger
{
 public void LogInfo(string message)
 {
 System.Console.WriteLine($"[+] {message}");
 }
}

Registering your services

private static IServiceProvider ConfigureServices()
{
 return new ServiceCollection()
 .AddSingleton<Logger>()
 .AddTransient<IRocket, Rocket>()
 // Call this, after you registered your services.
 .EnableDynamicProxy()
 .BuildServiceProvider();
}
public interface IRocket
{
 string Name { get; set; }
 void Launch();
}
// Enabled interception for service type IRocket
[Intercept(typeof(IRocket))]
public class Rocket: IRocket
{
 public string Name { get; set; }
 [Log]
 public void Launch()
 {
 System.Console.WriteLine("Launching rocket in 3...2.....1 πŸš€");
 }
}
static void Main(string[] args)
{
 var services = ConfigureServices();
 var rocket = services.GetRequiredService<IRocket>();
 rocket.Name = "Falcon 9";
 rocket.Launch();
 System.Console.WriteLine($"{rocket.Name} launched successfully. (:");
}

Sample Output

[+] [Log] Executing method: SharpAspect.Sample.Rocket.Launch
Launching rocket in 3...2.....1 πŸš€
Falcon 9 launched successfully. (:

About

AOP implementation for .Net

Topics

Resources

License

Stars

Watchers

Forks

Packages

Contributors 3

Languages

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /