Tag: 动态代理

如何在/ .Net中拦截来自/到第三方库的非虚拟方法的调用?

我认为我需要的是.net人称之为“透明动态代理”的东西,但我迄今为止看到的所有实现(Castle DynamicProxy,Spring.NET AOP等)都要求我至少执行以下其中一项: 将截获的方法声明为虚拟 包装类并创建包装器的实例而不是包装类 更改inheritance或实现接口 显然,如果调用者和被调用者都是非虚拟的,并且来自第三方封闭源库,那么我就无能为力。 如果C#是像Python这样的动态语言,我会这样做: foo = ThirdyPartyLibA.Foo() def interceptor(self, *args, **kwargs): do_something_before(self, *args, **kwargs) result = ThirdyPartyLibB.Bar.intercepted(self, *args, **kwargs) do_something_after(self, result, *args, **kwargs) return result foo.bar.intercepted = interceptor # bar is an instance of ThirdyPartyLibB.Bar foo.do_its_job() # Foo.do_its_job calls Bar.intercepted 我需要这个来改变ThirdyPartyLibA.Foo的不良行为,同时与ThirdyPartyLibB.Bar交互。 我确切知道导致这种行为的原因以及如何更改Foo或Bar来修复此错误,这要归功于dissasemblers。 一些(非常不可能工作)的想法: 反汇编ThirdyPartyLibA,在代码中进行更改并生成兼容的程序集(不太可能工作,因为它是一个强命名的程序集) 编辑二进制文件以使Foo的错误方法成为虚拟的,并改变它保持有效程序集所需的一切,这样我就可以使用动态代理(不太可能工作,也因为与上述想法相同的原因) 找到一个适合的透明动态代理实现(我认为没有基于这个论坛post: http : //www.pcreview.co.uk/forums/overriding-non-virtual-methods-using-il-and-reflection- emit-t2605695.html ) […]

在C#中实现动态代理的最佳方法是什么?

我需要在C#中创建动态代理。 我希望这个类包装另一个类,并采用它的公共接口,转发对这些函数的调用: class MyRootClass { public virtual void Foo() { Console.Out.WriteLine(“Foo!”); } } interface ISecondaryInterface { void Bar(); } class Wrapper : ISecondaryInterface where T: MyRootClass { public Wrapper(T otherObj) { } public void Bar() { Console.Out.WriteLine(“Bar!”); } } 这是我想要使用它的方式: Wrapper wrappedObj = new Wrapper(new MyRootClass()); wrappedObj.Bar(); wrappedObj.Foo(); 生产: Bar! Foo! 有任何想法吗? 最简单的方法是什么? 最好的方法是什么? 非常感谢。 […]

如何在Castle.DynamicProxy中使用IInterceptor?

我写了一个这样的例子 简单计算器类: public class Calculator { public int Add(int a, int b) { return a + b; } } 实现了DynamicProxy提供的“IInterceptor” [Serializable] public abstract class Interceptor : IInterceptor { public void Intercept(IInvocation invocation) { ExecuteBefore(invocation); invocation.Proceed(); ExecuteAfter(invocation); } protected abstract void ExecuteAfter(IInvocation invocation); protected abstract void ExecuteBefore(IInvocation invocation); } 创建了一个Interceptor类,并inheritance自“Interceptor”类 public class CalculatorInterceptor : Interceptor { […]

为什么不会为* each * virtual方法调用调用DynamicProxy的拦截器?

一个例子最好地解释了: public interface IA { void foo(); void bar(); } public class A : IA { public virtual void foo(){ Console.Write(“foo”); bar(); //call virtual method } public virtual void bar(){ Console.Write(“bar”); } } public class Interceptor : IInterceptor { public void Intercept(IInvocation invocation) { Console.WriteLine(“Intercepted: ” + invocation.Method.Name); invocation.Proceed(); } } Main(){ IA a = […]

如何在运行时替换方法实现?

我想拥有属性getter和方法,我可以用自己的自定义属性进行装饰,并根据该属性的存在,用不同的实现替换方法体。 此外,不同的实现需要知道赋予自定义属性的构造函数参数,在该属性中它装饰方法。 这显然可以通过AOP完成,比如PostSharp或LinFu,但是我想知道是否有一种方法可以做到这一点,不涉及构建后的处理步骤,因为添加使项目更加复杂化。