如何在C#中制作一个简单的动态代理 [英] How to make a simple dynamic proxy in C#

查看:32
本文介绍了如何在C#中制作一个简单的动态代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建一个动态代理对象来向对象添加某些功能.

I want to build a dynamic proxy object to add certain functionality to an object.

基本上我想接收一个对象,用一个看起来与我得到的原始对象相同的对象包装它,并拦截所有调用.

basically i want to receive an object, wrap it with an object that looks identical to the original i got, and intercept all the calls.

class Wrapper : DynamicProxy// dynamic proxy is not a reall class, but i guess something like this exists...
{
    public static T Wrap(T obj)
    {
        return (T) new Wrapper(obj);
    }

    public override object InterceptCall(MethodInfo info, object[] args)
    {
        // do stuff
    }

}

<小时>

澄清一下,我想做一些类似于 WCF 频道工厂的事情...


Just to clarify, I want to do something similar to the WCF channel factory...

我正在添加赏金,因为我需要一种很好的方法来代理类(而不是接口)和处理非虚拟方法(就像我在new"关键字下继承并添加了一个方法一样).我确信这一切都是有可能的,因为 .Net 做到了.

I'm adding a bounty, because I need a good way to proxy classes (not interfaces) and to handle non virtual methods (as if I inherited and added a methond under the "new" keyword). I'm sure all this is very possible as the .Net does it.

推荐答案

我应该早点写这个,但没关系.

I should have written this sooner, but never mind.

我的问题有一个特殊的问题",我需要能够代理类而不是接口.

My issue had a special "gotcha" I needed to be able to proxy classes and not interfaces.

有两种解决方案:

  1. RealProxy 和朋友们,基本上是指使用.NET Remoting.需要从 ContextBoundObject 继承.

  1. RealProxy and friends, basically means using .NET Remoting. Requires one to inherit from ContextBoundObject.

使用 System.Reflection 构建代理.像 spring<所做的那样发出/a> 你也可以看看他们的的代码代理工厂对象.这是另外三个文章主题.

Building a proxy using System.Reflection.Emit as done by spring you can also look at the code of their ProxyFactoryObject. Here are another three articles on the subject.

  • 这种方法的主要缺点是限制您只能覆盖virtual 成员.

这篇关于如何在C#中制作一个简单的动态代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆