My favorites | Sign in
Project Home Downloads Wiki Issues Source
Autofac can be used with Castle.Core DynamicProxy2 for AOP functionality.
Updated Jan 22, 2013 by travis.illig


DynamicProxy2, part of the from the Castle Project core, provides a method interception framework.

The Autofac.Extras.DynamicProxy2 integration enables method calls on Autofac components to be intercepted by other components. Common use-cases are transaction handling, logging, and declarative security.

Required References

The easiest way to add references to the required assemblies is to use NuGet. The instructions for that are below. If you are unable to use NuGet, instructions are also provided for manually adding the references

For NuGet, install the Autofac.Extras.DynamicProxy2 package. The appropriate references will be added to your project.

For manual references download both Autofac and Castle.Core. Add references to:

  • Autofac.dll
  • Autofac.Extras.DynamicProxy2.dll
  • Castle.Core.dll

Enabling Interception

The basic steps to get DynamicProxy2 integration working are:

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

Create Interceptors

Interceptors implement the Castle.!DynamicProxy.IInterceptor interface. Here's a simple interceptor example that logs method calls including inputs and outputs:

public class CallLogger : IInterceptor
    TextWriter _output;

    public CallLogger(TextWriter output)
        _output = output;

    public void Intercept(IInvocation invocation)
        _output.Write("Calling method {0} with parameters {1}... ",
            string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray()));


        _output.WriteLine("Done: result was {0}.", invocation.ReturnValue);

Register Interceptors with Autofac

Interceptors must be registered with the container. You can register them either as typed services or as named services. If you register them as named services, they must be named IInterceptor registrations.

Which of these you choose depends on how you decide to associate interceptors with the types being intercepted.

// Named registration
builder.Register(c => new CallLogger(Console.Out))

// Typed registration
builder.Register(c => new CallLogger(Console.Out));

Enable Interception on Types

When you register a type being intercepted, you have to mark the type at registration time so Autofac knows to wire up that interception. You do this using the EnableInterfaceInterceptors() and EnableClassInterceptors() registration extensions.

var builder = new ContainerBuilder(); 
builder.Register(c => new CallLogger(Console.Out));
var container = builder.Build();
var willBeIntercepted = container.Resolve<ISomeInterface>(); 

Under the covers, EnableInterfaceInterceptors() creates an interface proxy that performs the interception, while EnableClassInterceptors() dynamically subclasses the target component to perform interception of virtual methods.

Both techniques can be used in conjunction with the assembly scanning support, so you can configure batches of components using the same methods.

Special case: WCF proxy and remoting objects While WCF proxy objects look like interfaces, the EnableInterfaceInterceptors() mechanism won't work because, behind the scenes, .NET is actually using a System.Runtime.Remoting.TransparentProxy object that behaves like the interface. If you want interception on a WCF proxy, you need to use the InterceptTransparentProxy() method.

var cb = new ContainerBuilder();
cb.Register(c => CreateChannelFactory()).SingleInstance();
  .Register(c => c.Resolve<ChannelFactory<ITestService>>().CreateChannel())

Associate Interceptors with Types to be Intercepted

To pick which interceptor is associated with your type, you have two choices.

Your first option is to mark the type with an attribute, like this:

// This attribute will look for a TYPED
// interceptor registration:
public class First
  public virtual int GetValue()
    // Do some calculation and return a value

// This attribute will look for a NAMED
// interceptor registration:
public class Second
  public virtual int GetValue()
    // Do some calculation and return a value

When you use attributes to associate interceptors, you don't need to specify the interceptor at registration time. You can just enable interception and the interceptor type will automatically be discovered.

// Using the TYPED attribute:
var builder = new ContainerBuilder(); 
builder.Register(c => new CallLogger(Console.Out));

// Using the NAMED attribute:
var builder = new ContainerBuilder(); 
builder.Register(c => new CallLogger(Console.Out))

The second option is to declare the interceptor at Autofac registration time. You can do this using the InterceptedBy() registration extension:

var builder = new ContainerBuilder(); 
builder.Register(c => new CallLogger(Console.Out));


Use Public Interfaces

Interface interception requires the interface be public. Non-public interface types can't be intercepted.

Use Virtual Methods

Class interception requires the methods being intercepted to be virtual since it uses subclassing as the proxy technique.

Usage with Expressions

Components created using expressions, or those registered as instances, cannot be subclassed by the DynamicProxy2 engine. In these cases, it is necessary to use interface-based proxies.

Interface Registrations

To enable proxying via interfaces, the component must provide its services through interfaces only. For best performance, all such service interfaces should be part of the registration, i.e. included in As<X>() clauses.

WCF Proxies

As mentioned earlier, WCF proxies and other remoting types are special cases and can't use standard interface or class interception. You must use InterceptTransparentProxy() on those types.

Powered by Google Project Hosting