Castle Dynamic Proxy MixinInstance行为

问题描述 投票:0回答:1

[我正在使用Castle的DynamicProxy生成器在POCO类中与非虚拟成员作斗争,并使用下面的代码使用ProxyGenerationOptions.AddMixinInstance()找到了实现这一目标的方法。

我的问题是为什么,如果mixin可以将非虚拟成员发送给拦截器,那么基于我的实际类型,标准代理就不能了吗?

下面是代码。

void Main()
{
    var generator = new ProxyGenerator();

    Console.WriteLine(Environment.NewLine + "============ Proxy - With Target ===============");
    var person = new Person { Name = "Freddy FudPucker", Age = 62 };
    var personProxy = CreateProxyWithTarget(generator, person);


    Console.WriteLine(((IPerson)personProxy).Name);
    Console.WriteLine(((IPerson)personProxy).Age);
    ((IPerson)personProxy).Name = "Speedy";
    ((IPerson)personProxy).Age = 64;
    Console.WriteLine(((IPerson)personProxy).Name);
    Console.WriteLine(((IPerson)personProxy).Age);

    Console.WriteLine(((ITracking)personProxy).State);
    ((ITracking)personProxy).State = 1;
    Console.WriteLine(((ITracking)personProxy).State);
}

public object CreateProxyWithTarget(ProxyGenerator generator, Person person)
{
    var options = new ProxyGenerationOptions();
    options.AddMixinInstance(person);
    options.AddMixinInstance(new Tracking());
    return generator.CreateClassProxyWithTarget(typeof(ProxyBase), new[] { typeof(ITracking) }, new ProxyBase(), options, new PersonInterceptor());
}

哪个提供以下输出

Person System.String get_Name()
Freddy FudPucker
62
Person Void set_Name(System.String)
Person Void set_Age(Int32)
Person System.String get_Name()
Speedy
Person Int32 get_Age()
64
Person Int32 get_State()
0
Person Void set_State(Int32)
Person Int32 get_State()
1

下面是支持的类和接口

public class ProxyBase
{
    public ProxyBase()
    {

    }
}

public interface ITracking
{
    int State { get; set; }
}

public class Tracking : ITracking
{
    public int State { get; set; }
}


public class Person : IPerson
{
    public string Name { get; set; }

    public int Age { get; set; }
}

public interface IPerson
{
    string Name { get; set; }
    int Age { get; set; }
}

public interface IPersonAge
{
    int Age { get; set; }
}

class PersonInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        Console.WriteLine($"Person {invocation.Method}");
        invocation.Proceed();
    }
}
castle-dynamicproxy
1个回答
0
投票

您具有目标的类代理继承自您的ProxyBase类,因此需要虚拟成员,而DynamicProxy mixins在该代理类上实现mixin类的接口的成员,因此是隐式虚拟的。

// You can do this (from your example):
Console.WriteLine(((IPerson)personProxy).Name);

// ... but not this (because the proxy isn't a Person but is an IPerson):
Console.WriteLine(((Person)personProxy).Name);

AddMixinInstance的XML文档具有更多详细信息:https://github.com/castleproject/Core/blob/e2dfb57020d9dbb4b31f3ce548b34cb35ffa3307/src/Castle.Core/DynamicProxy/ProxyGenerationOptions.cs#L208-L225

© www.soinside.com 2019 - 2024. All rights reserved.