Selectively intercepting methods using autofac and dynamicproxy2
I am currently experimenting a bit using Autofac-1.4.5.676, autofac contrib and DynamicProxy2 lock. The goal is to create a coarse-grained profiler that can intercept calls to specific methods of a specific interface.
Problem: everything works fine for me separately from the electoral part. I could be wrong, but I think I need to marry my interceptor using the IProxyGenerationHook implementation, but I cannot figure out how.
My code looks something like this:
The interface to be intercepted and profiled (note that I only need to profile the Update () method )
public interface ISomeSystemToMonitor
{
void Update(); // this is the one I want to profile
void SomeOtherMethodWeDontCareAboutProfiling();
}
Now, when I register my systems with a container, I do the following:
// Register interceptor gubbins
builder.RegisterModule(new FlexibleInterceptionModule());
builder.Register<PerformanceInterceptor>();
// Register systems (just one in this example)
builder.Register<AudioSystem>()
.As<ISomeSystemToMonitor>)
.InterceptedBy(typeof(PerformanceInterceptor));
All instances of ISomeSystemToMonitor pulled from the container are intercepted and profiled at will, except that it intercepts all of its methods, not just the Update method.
Now, how can I extend this to exclude all methods other than Update ()? As I said, I don't understand how I should tell the container that "for ProfileInterceptor, use this IProxyHookGenerator implementation".
All help is appreciated, welcome! Also, please note that I cannot switch to autofac2.x right now; I am stuck with 1.
a source to share
A IProxyGenerationHook
instance must be passed in when called CreateInterfaceProxyWithTarget
when the interceptor is created. See this tutorial for details .
There is currently no way to provide such interceptions without changes in the Autofac.DynamicProxy2 integration module. May be a nice addition to the extension InterceptedBy
.
Alternatively, you can create filtering in PerformanceInterceptor
. Looking at IInvocation
, you are passed in when called, examine the property Method
to decide whether to profile or not. But this, of course, will be less effective than bypassing the interception at the proxy level.
a source to share
For DynamicProxy2, the method EnableInterfaceInterceptors
now has an overload that takes an object ProxyGenerationOptions
.
//Define the builder
var builder = new ContainerBuilder();
//Instantiate your Proxy options with a selector
var proxyOptions = new ProxyGenerationOptions {Selector = new MyInterceptSelector()};
//Pass the proxy options as a parameter to the EnableInterfaceInterceptors method
builder.RegisterType<MyRepo>()
.As<IMyRepo>()
.EnableInterfaceInterceptors(proxyOptions)
.InterceptedBy(typeof(IInterceptor));
a source to share