在.NET中动态拦截调用 [英] Dynamic interception of calls in .NET
问题描述
如果没有,C#4.0中的新的动态类型对象功能将在此帮助
没有任何内置的东西可以拦截你不能控制实例化的对象。同样地,在即将到来的.net 4.0中也没有新的设施。
如果您可以控制实例化:
- 如果您的对象可以是MarshalByRef可以使用 RealProxy 。
- 您可以使用不少IOC容器,例如 LinFu ,城堡动态代理
- 您可以使用像 PostSharp , Mono Cecil 或微软CCI 将作为后期编译步骤的截取重写程序集。
如果您无法控制实例化
- 您可以使用 ICorDebug - .Net调试很难使用和沉重的API。
- 您可以使用 ICorProfiler - .Net分析API,使用起来也很复杂。另外,您可以看一下动态语言,如IronRuby,它具有内置的
alias_method
和define_method
goodness(允许您重新定义任何东西),所以拦截在。
.NET 4.5引入了一种方法来 ReJIT 方法,为方法拦截提供了另一个钩子(前提是您没有运行并发/ bg GC,方法没有内联)
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).
If not, would the new 'Dynamically Typed Objects' feature in C# 4.0 help in this regard.
解决方案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.
If you can control instantiation:
- If your object can be MarshalByRef you can use RealProxy.
- You could use quite a few IOC containers, eg. LinFu, Castle Dynamic Proxy
- You could use a tool like PostSharp, Mono Cecil or Microsoft CCI to rewrite your assemblies with the interceptions as a post compile step.
If you can not control instantiation
- You can use ICorDebug - the .Net debugging APIs which are really hard to use and heavy.
- You can use ICorProfiler - the .Net profiling APIs where are also pretty complicated to use.
Alternatively, you could look at a dynamic language like IronRuby, which has a built-in
alias_method
anddefine_method
goodness (which allows you to redefine anything), so interception baked in.
.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中动态拦截调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!