AOP (Aspect Oriented Programming) using dotnet source generator.
Including extensions for Autofac, but any implementation that calls the generated code would do.
Usage example, logging all calls to console:
Saspect/Saspect.Test/SampleTest.cs
Lines 8 to 45 in 6e61f79
public class MyService | |
{ | |
[Log] | |
public virtual void MyMethod() | |
{ | |
} | |
} | |
public class LogAttribute() : AspectAttribute(typeof(LogAspect)); | |
public class LogAspect : IAspect | |
{ | |
public void OnBeforeInvocation(InvocationInfo invocation) | |
{ | |
Console.WriteLine($"{invocation.Method.Name} is invoked"); | |
} | |
public void OnAfterInvocation(Exception exception, InvocationInfo invocation) | |
{ | |
Console.WriteLine($"{invocation.Method.Name} exited"); | |
} | |
} | |
public class SampleTest | |
{ | |
[Test] | |
public void ShouldLogMethodCallToConsole() | |
{ | |
var builder = new ContainerBuilder(); | |
builder.RegisterType<AspectInterceptor>(); | |
builder.RegisterType<LogAspect>().As<IAspect>(); | |
builder.RegisterType<MyService>().ApplyAspects(); | |
var container = builder.Build(); | |
var target = container.Resolve<MyService>(); | |
target.MyMethod(); | |
} | |
} |