本文介绍了在.NET中调用动态拦截的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇,想了解是否.NET支持任何形式的方法调用(或属性调用)在运行时动态拦截。也就是说,可以拦截调用而不静态编译信息的对象,例如(一个接口(沿CORBA DII的线的)或COM的IDispatch)。

I am curious to learn if .NET supports any form of dynamic interception of method calls (or properties invocations) at runtime. That is, can you intercept a call to an object without static compilation information such as an interface (along the lines of the CORBA DII (link text) or COM's IDispatch).

如果不是,将新的动态类型对象在这方面,C#4.0的帮助功能。

If not, would the new 'Dynamically Typed Objects' feature in C# 4.0 help in this regard.

推荐答案

没有什么内置的,可以让你拦截,你无法控制的实例化一个对象。同样,将有此在即将到来的.NET 4.0没有新的设施。

There is nothing built-in that allows you to intercept an object that you can not control instantiation of. Similarly, there will be no new facilities for this in the upcoming .net 4.0.

如果你能控制实例:

  1. 如果你的对象可以是MarshalByRef可以使用 RealProxy
  2. 您可以用相当多的IOC容器,例如。 李林甫,的
  3. 您可以使用如 PostSharp 的一个工具,的或Microsoft CCI 来重写你的组件与拦截作为后编译步骤。
  1. If your object can be MarshalByRef you can use RealProxy.
  2. You could use quite a few IOC containers, eg. LinFu, Castle Dynamic Proxy
  3. You could use a tool like PostSharp, Mono Cecil or Microsoft CCI to rewrite your assemblies with the interceptions as a post compile step.

如果你无法控制的实例

  1. 您可以使用 ICorDebug - 的净调试的API这是真的很难使用和沉重。
  2. 您可以使用 ICorProfiler - 的净分析的API,其中也pretty的复杂使用。
  1. You can use ICorDebug - the .Net debugging APIs which are really hard to use and heavy.
  2. You can use ICorProfiler - the .Net profiling APIs where are also pretty complicated to use.

另外,你可以看一个动态语言如IronRuby的,它有一个内置的 alias_method define_method 善良(它允许你重新定义任何东西),所以拦截烤

Alternatively, you could look at a dynamic language like IronRuby, which has a built-in alias_method and define_method goodness (which allows you to redefine anything), so interception baked in.

.NET 4.5中引入的方法的方法,它提供了另一种钩子拦截的方法(前提是你没有运行并发/ BG GC和方法是不是内联)

.NET 4.5 is introducing a method to ReJIT methods which provides another hook for method interception (provided you are not running a concurrent/bg GC and the method is not inlined)

这篇关于在.NET中调用动态拦截的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 11:39