Autofac with method interception for logging

Tags: Autofac, Logging

Are you currently using autofac and looking for a way to make logging easier?  Nicholas Blumhardt did a really great job documenting this process on the autofac site. However, I thought I would put together a functional example to download with a way of easily executing interception for you to download since a few colleagues of mine struggled when first learning autofac on how to accomplish interception fast and easy.

Download the Example

My example is a console application for simplicity but can easily be tweaked to the format of any web or desktop application solution. I used Nicholas’s intercept method example which will write out the method name being called and the methods parameters before the execution of the method. Then writes out the result when the method is done being executed.

//The interceptor will log the beginning and end of the method call.
public void Intercept(IInvocation invocation)
    //This happens before the method call
    _output.Write("Calling method {0} with parameters {1}... ",
    string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray()));

    //Actual method call begins

    //This happens after a method call
    _output.WriteLine("Done: result was {0}.", invocation.ReturnValue);

My repository is simple, it will return a simple list of state names in string type format. On the interface for the repository I add the intercept attribute necessary to do the interception on all methods within the repository.

public class ConsoleRepository : IConsoleRepository
    /// <summary>
    /// Just a generic collection of states
    /// </summary>
    /// <returns></returns>
    public IEnumerable<string> GetListOfStates()
        return new List<string> {"State 1", "State 2", "State 3", "State 4"};

//the intercept can be on the interface of the class
public interface IConsoleRepository
    IEnumerable<string> GetListOfStates();

My console app is really simple, I create an autofac container, register my interceptor (tell it to publish the output to the console), register my repository and finally create the container for my application. My application will call the WriteOutStates method call which will write out each state name to the console.

static void Main()
    //Create the Autofac Container
    var builder = new ContainerBuilder();

    //Register the Log Interceptor, which will log out to the console of the application. Anything registered with 'log-calls' will be intercepted
    builder.Register(c => new LogInterceptor(Console.Out))

    //Register the repository, make sure 'EnableInterfaceInterceptors' is called, this is important in letting Castle know it has Interceptors
    builder.Register(c => new ConsoleRepository())

    //Build the container
    using (var container = builder.Build())

private static void WriteOutStates(IComponentContext container)
    //pull the registered repository from the Autofac container
    var consoleRepo = container.Resolve<IConsoleRepository>();

    //This method call to get the list of states will be intercepted.
    foreach (var state in consoleRepo.GetListOfStates())

The WriteOutStates method will make the call to the repository where we are expecting the interception to take place. When it makes the call to get the list of states from the repository we are expecting to see the name of the method being called and the result when its finished. Then we it will write each state out to the console. Here is what it will look like after executing the application.


Download the application and play around with it. I hope it helps you out on when getting started with interception using autofac!


  • Michael said

    Mark, Thanks for the article. Any chance you could either provide the actual dependencies in the download, or name them? I cannot get this source to work with the current versions of autofac, castle.core etc.

  • Michael said

    To be more specific. Im having problems when trying to add the autofac contrib via Nuget.. Install-Package : Updating 'Castle.Core' to 'Castle.Core 1.2.0' failed. Unable to find a version of 'AutofacContrib.DynamicProxy2' that is compatible with 'Castle.Core 1.2.0'

    If I ignore dependencies during package install then I just run into more problems in the code, so I am wondering what versions of all dependencies you are using. Thanks

  • mjourdan said

    @Michael I'm sorry you're running into problems. I've gone ahead and re-packaged a new download with all the dependencies included in it. I should have shared the trick I had to run to attach the dependencies. In the package console you can run the following command which ignores the dependency check on that package "install-package autofaccontrib.dynamicproxy2 -ignoredependencies"

    Please download the new source code and let me know if you have any more trouble. Thanks for reading and enjoy!

  • Michael said

    Marc, thank you for uploading the new source. This is now working perfectly for me. I was using the -ignoredependencies flag as I had seen this used in another article however this still did not work. On another note, did you try this approach with the latest version of Autofac (version 3.0)? Im getting an exception when the container builder trys to register the repository

    ..The type initializer for 'AutofacContrib.DynamicProxy2.RegistrationExtensions' threw an exception.
    Could not load file or assembly 'Castle.Core, Version=, Culture=neutral. I think that AutofacContrib may not have been updated in a while. Thanks for your help guys. Michael

  • Michael said

    Sorry Guys, just noticed a mistake.
    "On another note, did you try this approach with the latest version of Autofac (version 3.0)? "

    Was meant to be "did you try this approach with Castle.Core (version 3.0) " not Autofac.

Add a Comment