Type Interceptors
Enabling Interception
Create Interceptors
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}... " ,
invocation . Method . Name ,
string . Join ( ", " , invocation . Arguments . Select ( a => ( a ?? "" ). ToString ()). ToArray ()));
invocation . Proceed ();
_output . WriteLine ( "Done: result was {0}." , invocation . ReturnValue );
}
}
Register Interceptors with Autofac
// Named registration
builder . Register ( c => new CallLogger ( Console . Out ))
. Named < IInterceptor > ( "log-calls" );
// Typed registration
builder . Register ( c => new CallLogger ( Console . Out ));
Enable Interception on Types
var builder = new ContainerBuilder ();
builder . RegisterType < SomeType > ()
. As < ISomeInterface > ()
. EnableInterfaceInterceptors ();
builder . Register ( c => new CallLogger ( Console . Out ));
var container = builder . Build ();
var willBeIntercepted = container . Resolve < ISomeInterface > ();
var cb = new ContainerBuilder ();
cb . RegisterType < TestServiceInterceptor > ();
cb . Register ( c => CreateChannelFactory ()). SingleInstance ();
cb
. Register ( c => c . Resolve < ChannelFactory < ITestService >> (). CreateChannel ())
. InterceptTransparentProxy ( typeof ( IClientChannel ))
. InterceptedBy ( typeof ( TestServiceInterceptor ))
. UseWcfSafeRelease ();
Associate Interceptors with Types to be Intercepted
// This attribute will look for a TYPED
// interceptor registration:
[Intercept(typeof(CallLogger))]
public class First
{
public virtual int GetValue ()
{
// Do some calculation and return a value
}
}
// This attribute will look for a NAMED
// interceptor registration:
[Intercept("log-calls")]
public class Second
{
public virtual int GetValue ()
{
// Do some calculation and return a value
}
}
// Using the TYPED attribute:
var builder = new ContainerBuilder ();
builder . RegisterType < First > ()
. EnableClassInterceptors ();
builder . Register ( c => new CallLogger ( Console . Out ));
// Using the NAMED attribute:
var builder = new ContainerBuilder ();
builder . RegisterType < Second > ()
. EnableClassInterceptors ();
builder . Register ( c => new CallLogger ( Console . Out ))
. Named < IInterceptor > ( "log-calls" );
var builder = new ContainerBuilder ();
builder . RegisterType < SomeType > ()
. EnableClassInterceptors ()
. InterceptedBy ( typeof ( CallLogger ));
builder . Register ( c => new CallLogger ( Console . Out ));
Tips
Use Public Interfaces
Use Virtual Methods
Usage with Expressions
Interface Registrations
WCF Proxies
Class Interceptors and UsingConstructor
Known Issues
Asynchronous Method Interception
Castle.Core Versioning