Autofac拦截目标方法

时间:2015-02-26 17:36:02

标签: c# aop autofac interceptor castle-dynamicproxy

我使用Autofac.Extras.DynamicProxy2对服务实现执行某些方法拦截。

该服务有很多方法,我只想针对一些。

除了针对我想拦截的方法的已批准字符串字典检查调用目标名称之外,还有更好的做法吗?

   public void Intercept(IInvocation invocation)
    {
        invocation.Proceed();
        if (ContinueIntercept(invocation))
        {
            // Do intercept work
        }
    }

    private bool ContinueIntercept(IInvocation invocation)
    {            
        // Logic to compare invocation.MethodInvocationTarget.Name 
    }

它实际上并没有增加所有这些,但它仍然感觉像是一种糟糕的方式。特别是因为将其添加到特定服务实现意味着它将拦截基类公共实现的所有方法调用。如果只拦截派生类,那就不会那么糟糕。

我看到Castle.DynamicProxy2有办法指定调用目标,但我不知道如何用autofac连接它。

1 个答案:

答案 0 :(得分:4)

您可以使用IProxyGenerationHook指定ProxyBuilder应生成代理的方法。

public class FooProxyGenerationHook : IProxyGenerationHook
{
    public void MethodsInspected()
    { }

    public void NonProxyableMemberNotification(Type type, MemberInfo memberInfo)
    { }

    public Boolean ShouldInterceptMethod(Type type, MethodInfo methodInfo)
    {
        if (type == typeof(Foo) && methodInfo.Name == "Do")
        {
            return true;
        }
        return false;
    }
}

然后,您可以这样注册:

    ProxyGenerator generator = new ProxyGenerator();
    FooProxyGenerationHook hook = new FooProxyGenerationHook();
    IFoo foo = generator.CreateClassProxyWithTarget<Foo>(new Foo(), new ProxyGenerationOptions(hook), new FooInterceptor());

为了避免为每个代理调用IProxyGenerationHook,您应该只有一个hook实例。

使用DynamicProxy2,您可以使用以下代码:

    FooProxyGenerationHook hook = new FooProxyGenerationHook();

    ContainerBuilder builder = new ContainerBuilder();
    builder.RegisterType<FooInterceptor>().AsSelf();
    builder.RegisterType<Foo>().As<IFoo>()
            .EnableClassInterceptors(new ProxyGenerationOptions(hook))
            .InterceptedBy(typeof(FooInterceptor));