Castle dynamicproxy Castle动态代理混合实例行为
我正在使用Castle的DynamicProxyGenerator与POCO类中的非虚拟成员进行斗争,并找到了一种方法,使用Castle dynamicproxy Castle动态代理混合实例行为,castle-dynamicproxy,Castle Dynamicproxy,我正在使用Castle的DynamicProxyGenerator与POCO类中的非虚拟成员进行斗争,并找到了一种方法,使用ProxyGenerationOptions.AddMixiInstance()实现这一点,使用下面的代码 我的问题是,如果mixin可以将非虚拟成员发送到拦截器,那么基于我的实际类型的标准代理为什么不能呢? 下面是代码 void Main() { var generator = new ProxyGenerator(); Console.WriteLin
ProxyGenerationOptions.AddMixiInstance()
实现这一点,使用下面的代码
我的问题是,如果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();
}
}
带有目标的类代理继承自
ProxyBase
类,因此需要虚拟成员,而DynamicProxy mixin在该代理类上实现mixin类接口的成员,因此是隐式虚拟的。有效地混合就像目标的接口代理一样工作
//您可以这样做(从您的示例中):
Console.WriteLine(((IPerson)personProxy.Name);
// ... 但不是这样(因为代理不是个人,而是个人):
Console.WriteLine(((个人)personProxy.Name);
addMixiInstance
的XML文档有一些更详细的内容: