【问题标题】:Intercepting method from abstract parent on derived instance using DynamicProxy使用 DynamicProxy 从派生实例上的抽象父级拦截方法
【发布时间】:2011-09-01 18:49:03
【问题描述】:

我有一个从抽象基类派生的对象,我想截取该对象的方法。

DynamicProxy 是否支持这种情况?我似乎只能通过接口或没有目标来创建代理,但不能通过抽象基类 with 一个目标

public abstract class Sandwich
{
    public abstract void ShareWithFriend();
}

public sealed class PastramiSandwich : Sandwich
{
    public override void ShareWithFriend()
    {
        throw new NotSupportedException("No way, dude");
    }
}

class SandwichInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        try
        {
            invocation.Proceed();
        }
        catch (NotSupportedException)
        {
            // too bad
        }
    }
}

internal class Program
{
    private static void Main()
    {
        var sandwich = new PastramiSandwich();
        var generator = new ProxyGenerator();

        // throws ArgumentException("specified type is not an interface")
        var proxy1 = generator.CreateInterfaceProxyWithTarget<Sandwich>(
            sandwich,
            new SandwichInterceptor());
        proxy1.ShareWithFriend();

        // does not accept a target
        var proxy2 = generator.CreateClassProxy<Sandwich>(
            /* sandwich?, */
            new SandwichInterceptor());
        // hence the method call fails in the interceptor
        proxy2.ShareWithFriend();
    }
}

【问题讨论】:

    标签: abstract-class castle-dynamicproxy


    【解决方案1】:

    这行得通:

    var proxy1 = generator.CreateClassProxyWithTarget<Sandwich>(
        sandwich,
        new SandwichInterceptor());
    proxy1.ShareWithFriend();
    

    【讨论】:

    • 谢谢。该方法在我在 Nuget (Castle.DynamicProxy) 上找到的版本上不可用。使用更新的 Castle.Core 解决了这个问题 :)
    • 啊好的。 Castle.DynamicProxy 包已过时,正如它的描述所说......在 nuget 中没有办法让它更明显,或者重定向到 castle.core nuget,这让人们遇到了这个问题:|
    猜你喜欢
    • 1970-01-01
    • 2012-12-26
    • 2018-06-23
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    相关资源
    最近更新 更多