Autofac with method interception for logging

An easy approach to logging using method interception in Autofac

April 01, 2012

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.

View the Source Code

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}... ",
	invocation.Method.Name,
	string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray()));
		
	//Actual method call begins
	invocation.Proceed();
	
	//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
[Intercept("log-calls")]
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))
		.Named<IInterceptor>("log-calls");
	
	//Register the repository, make sure 'EnableInterfaceInterceptors' is called, this is important in letting Castle know it has Interceptors
	builder.Register(c => new ConsoleRepository())
		.As<IConsoleRepository>()
		.EnableInterfaceInterceptors();
		
	//Build the container
	using (var container = builder.Build())
	{
		WriteOutStates(container);
	}  
}
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())
	{
		Console.WriteLine(state);
	}
}

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!