动态创建代理类

时间:2013-03-31 20:03:24

标签: c# .net reflection proxy

我正在尝试动态创建代理类。我知道有一些非常好的框架可以做到这一点,但这纯粹是一个宠物项目,作为一个学习练习,所以我想自己做。

例如,如果我有以下类实现接口:

interface IMyInterface
{
    void MyProcedure();
}

class MyClass : IMyInterface
{
    void MyProcedure()
    {
        Console.WriteLine("Hello World");
    }
}

为了拦截这个类的方法以便记录它们,我创建了另一个类(我的代理类版本),它实现了相同的接口,但包含对“真实”类的引用。该类执行一个动作(例如记录),然后在真实类上调用相同的方法。

例如:

class ProxyClass : IMyInterface
{
    private IMyInterface RealClass { get; set; }

    void MyProcedure()
    {
        // Log the call
        Console.WriteLine("Logging..");

        // Call the 'real' method
        RealClass.MyProcedure();
    }
}

然后调用者调用代理类上的所有方法(我使用基本的home-brew IoC容器来代替实际类注入代理类)。我正在使用此方法,因为我希望能够在运行时将RealClass换成另一个实现相同接口的类。

有没有办法在运行时创建ProxyClass并填充其RealClass属性,以便它可以用作真实类的代理?有没有一种简单的方法可以做到这一点,还是需要使用像Reflection.Emit这样的东西并生成MSIL?

4 个答案:

答案 0 :(得分:51)

看看System.Runtime.Remoting.Proxies.RealProxy。您可以使用它从调用者的角度创建一个看似是目标类型的实例。 RealProxy.Invoke提供了一个点,您可以在该点上简单地调用基础类型上的目标方法,或者在调用之前/之后执行其他处理(例如,记录)。

以下是在每次方法调用之前/之后记录到控制台的代理示例:

public class LoggingProxy<T> : RealProxy
{
    private readonly T _instance;

    private LoggingProxy(T instance)
        : base(typeof(T))
    {
        _instance = instance;
    }

    public static T Create(T instance)
    {
        return (T)new LoggingProxy<T>(instance).GetTransparentProxy();
    }

    public override IMessage Invoke(IMessage msg)
    {
        var methodCall = (IMethodCallMessage)msg;
        var method = (MethodInfo)methodCall.MethodBase;

        try
        {
            Console.WriteLine("Before invoke: " + method.Name);
            var result = method.Invoke(_instance, methodCall.InArgs);
            Console.WriteLine("After invoke: " + method.Name);
            return new ReturnMessage(result, null, 0, methodCall.LogicalCallContext, methodCall);
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: " + e);
            if (e is TargetInvocationException && e.InnerException != null)
            {
                return new ReturnMessage(e.InnerException, msg as IMethodCallMessage);
            }

            return new ReturnMessage(e, msg as IMethodCallMessage);
        }
    }
}

以下是您将如何使用它:

IMyInterface intf = LoggingProxy<IMyInterface>.Create(new MyClass());
intf.MyProcedure();

然后输出到控制台:

在调用之前:MyProcedure
你好世界
调用后:MyProcedure

答案 1 :(得分:1)

您可以按照in this question所述使用动态对象,但对于动态生成的强类型对象,您必须使用Reflection.Emit,如您所怀疑的那样。 This blog有示例代码,显示了Type的动态创建和实例化。

我已经读过Roslyn具有使动态代理创建更容易的功能,所以也许可以看一下。

答案 2 :(得分:0)

也许我误解了这个问题,构造函数怎么样?

class ProxyClass : IMyInterface
{
    public ProxyClass(IMyInterface someInterface)
    {
        RealClass = someInterface;
    }
   // Your other code...
}

答案 3 :(得分:0)

我不建议这样做。通常您使用一些着名的库,如Castle或EntLib。对于一些复杂的类,动态生成代理可能是一个很大的挑战。以下是使用“Is”多态性执行此操作的示例。为此,您必须将基础中的所有方法声明为虚拟。你尝试这样做的方式(“有”)也是可能的,但对我来说看起来更复杂。

public class A
{
    public virtual void B()
    {
        Console.WriteLine("Original method was called.");
    }
}

class Program
{

    static void Main(string[] args)
    {
        // Create simple assembly to hold our proxy
        AssemblyName assemblyName = new AssemblyName();
        assemblyName.Name = "DynamicORMapper";
        AppDomain thisDomain = Thread.GetDomain();
        var asmBuilder = thisDomain.DefineDynamicAssembly(assemblyName,
                     AssemblyBuilderAccess.Run);

        var modBuilder = asmBuilder.DefineDynamicModule(
                     asmBuilder.GetName().Name, false);

        // Create a proxy type
        TypeBuilder typeBuilder = modBuilder.DefineType("ProxyA",
           TypeAttributes.Public |
           TypeAttributes.Class |
           TypeAttributes.AutoClass |
           TypeAttributes.AnsiClass |
           TypeAttributes.BeforeFieldInit |
           TypeAttributes.AutoLayout,
           typeof(A));
        MethodBuilder methodBuilder = typeBuilder.DefineMethod("B", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.ReuseSlot);
        typeBuilder.DefineMethodOverride(methodBuilder, typeof(A).GetMethod("B"));


        // Generate a Console.Writeline() and base.B() calls.
        ILGenerator ilGenerator = methodBuilder.GetILGenerator();
        ilGenerator.Emit(OpCodes.Ldarg_0);
        ilGenerator.EmitWriteLine("We caught an invoke! B method was called.");

        ilGenerator.EmitCall(OpCodes.Call, typeBuilder.BaseType.GetMethod("B"), new Type[0]);
        ilGenerator.Emit(OpCodes.Ret);

        //Create a type and casting it to A. 
        Type type = typeBuilder.CreateType();
        A a = (A) Activator.CreateInstance(type);

        // Test it
        a.B();
        Console.ReadLine();
    }
}