【问题标题】:Intercepting explicit interface implementations with Castle Dynamic Proxy使用 Castle Dynamic Proxy 拦截显式接口实现
【发布时间】:2012-06-01 14:17:52
【问题描述】:

我无法让 Castle Dynamic Proxy 拦截显式接口实现的方法。我在这里读到http://kozmic.pl/category/dynamicproxy/ 应该可以做到这一点。 这是我的课程;

internal interface IDomainInterface
{
    string DomainMethod();
}

public class DomainClass : IDomainInterface
{
    string IDomainInterface.DomainMethod()
    {
        return "not intercepted";
    }
}

这是我的拦截器类;

public class DomainClassInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        if (invocation.Method.Name == "DomainMethod")
            invocation.ReturnValue = "intercepted";
        else
            invocation.Proceed();
    }
}

这是我的测试(失败);

    [TestClass]
    public void can_intercept_explicit_interface_implementation()
    {
        // Create proxy
        var generator = new ProxyGenerator();
        var interceptor = new DomainClassInterceptor();
        var proxy = (IDomainInterface)generator.CreateClassProxy(typeof(DomainClass), interceptor);

        // Invoke proxy method
        var result = proxy.DomainMethod();

        // Check method was intercepted -- fails
        Assert.AreEqual("intercepted", result);
    }

除了无法拦截显式接口实现之外,我似乎也没有收到不可代理成员的通知。 这是我的代理生成钩子(充当间谍);

public class DomainClassProxyGenerationHook : IProxyGenerationHook
{
    public int NonProxyableCount;

    public void MethodsInspected() {}

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

    public bool ShouldInterceptMethod(Type type, MethodInfo methodInfo)
    {
        return true;
    }
}

这是我的测试(再次失败);

    [TestMethod] 
    public void receive_notification_of_nonproxyable_explicit_interface_implementation()
    {
        // Create proxy with generation hook
        var hook = new DomainClassProxyGenerationHook();
        var options = new ProxyGenerationOptions(hook);
        var generator = new ProxyGenerator();
        var interceptor = new DomainClassInterceptor();
        var proxy = (IDomainInterface)generator.CreateClassProxy(typeof(DomainClass), options, interceptor);

        // Check that non-proxyable member notification was received -- fails
        Assert.IsTrue(hook.NonProxyableCount > 0);
    }

有没有人成功让 DP 拦截显式接口实现?如果有,怎么做?

【问题讨论】:

    标签: castle-windsor castle-dynamicproxy


    【解决方案1】:

    您正在创建一个类代理。类代理只拦截类上的虚方法,C#中接口方法的显式实现根据定义不是虚的(因为它是私有的)。

    如果你想拦截接口上的方法,你需要明确告诉 DynamicProxy

    var proxy = (IDomainInterface)generator.CreateClassProxy(typeof(DomainClass), new Type[] { typeof(IDomainInterface) }, interceptor);
    

    此外,您的接口被标记为 internal,因此请确保 DynamicProxy 为 public(将接口设为公开或添加 InternalsVisibleToAttribute)。

    这样你的第一个测试就会通过,方法就会被拦截。

    【讨论】:

    • 是的,这正是我想要的。谢谢。
    猜你喜欢
    • 2011-10-03
    • 2018-01-30
    • 1970-01-01
    • 2013-11-08
    • 2011-09-30
    • 1970-01-01
    • 2011-10-01
    • 2011-09-05
    • 1970-01-01
    相关资源
    最近更新 更多