Last Updated: September 09, 2019
· carlosomar2

Aspect Oriented Programming on .Net Core

AOP is quite useful when used correctly. Here's how to do it using AutoFac and DynamicProxy.

First add Autofac.Extras.DynamicProxy Nuget package to your project.

There are four steps to implementing interception using DynamicProxy,

  • Create Interceptors.
  • Register Interceptors with Autofac.
  • Enable Interception on Types.
  • Associate Interceptors with Types to be Intercepted.

Create an interceptor. Here's a sample for a logger.

public class Logger: IInterceptor
 TextWriter writer;
 public Logger(TextWriter writer)
     if(writer == null){
        throw new ArgumentNullException(nameof(writer));
     this.writer = writer
 public void Intercept(IInvocation invocation)
    var name = $"{invocation.Method.DeclaringType}.{invocation.Method.Name}";
    var args = string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()));
    writer.WriteLine($"Calling: {name}");
    writer.WriteLine($"Args: {args}");
    var watch = System.Diagnostics.Stopwatch.StartNew();
    invocation.Proceed(); //Intercepted method is executed here.
    var executionTime = watch.ElapsedMilliseconds;

    writer.WriteLine($"Done: result was {invocation.ReturnValue}");
    writer.WriteLine($"Execution Time: {executionTime} ms.");

Finally, having the class and interfaces below, register the interception using our logger from above.

public interface ICalculator {
   int add(int a, int b);
public class Calculator : ICalculator
   public int add(int a, int b)
      return a + b;

Register interception

var b = new ContainerBuilder();
b.Register(i=> new Logger(Console.Out));

var container = b.Build();

You can see more about this in this post. It has more examples of usages for interceptors.