[英]How to avoid double construction of proxy with DynamicProxy::CreateClassProxyWithTarget?
I am decorating an existing object using the CreateClassProxyWithTarget
method. 我正在使用
CreateClassProxyWithTarget
方法装饰现有对象。 However, the constructor and therefore, initialization code, is being called twice. 但是,构造函数以及因此的初始化代码被调用了两次。 I already have a "constructed" instance (the target).
我已经有一个“构造”实例(目标)。 I understand why this happens, but is there a way to avoid it, other than using an empty constructor?
我知道为什么会发生这种情况,但是除了使用空的构造函数之外,还有其他方法可以避免这种情况吗?
Edit: Here is some code: 编辑:这是一些代码:
First the proxy creation: 首先创建代理:
public static T Create<T>(T i_pEntity) where T : class
{
object pResult = m_pGenerator.CreateClassProxyWithTarget(typeof(T),
new[]
{
typeof(IEditableObject),
typeof(INotifyPropertyChanged) ,
typeof(IMarkerInterface),
typeof(IDataErrorInfo)
},
i_pEntity,
ProxyGenerationOptions.Default,
new BindingEntityInterceptor<T>(i_pEntity));
return (T)pResult;
}
I use this for example with an object of the following class: 我将此示例与以下类的对象一起使用:
public class KatalogBase : AuditableBaseEntity
{
public KatalogBase()
{
Values = new HashedSet<Values>();
Attributes = new HashedSet<Attributes>();
}
...
}
If i now call BindingFactory.Create(someKatalogBaseObject);
如果我现在调用
BindingFactory.Create(someKatalogBaseObject);
the Values
and Attributes
properties are beeing initialized again. Values
和Attributes
属性将重新初始化。
Based off one of Krzysztof's articles and his comment on the Moq forum, I have managed to get this working: 基于Krzysztof的一篇文章和他在Moq论坛上的评论 ,我设法使这一工作得以实现:
class MyProxyGenerator : ProxyGenerator
{
public object CreateClassProxyWithoutRunningCtor(Type type, ProxyGenerationOptions pgo, SourcererInterceptor sourcererInterceptor)
{
var prxType = this.CreateClassProxyType(type, new Type[] { }, pgo);
var instance = FormatterServices.GetUninitializedObject(prxType);
SetInterceptors(instance, new IInterceptor[]{sourcererInterceptor});
return instance;
}
private void SetInterceptors(object proxy, params IInterceptor[] interceptors)
{
var field = proxy.GetType().GetField("__interceptors");
field.SetValue(proxy, interceptors);
}
}
So what you're asking is if DynamicProxy can construct the proxy instance without calling its constructor? 因此,您要问的是DynamicProxy是否可以在不调用其构造函数的情况下构造代理实例?
That is not really possible. 那是不可能的。 There is a way using
FormatterServices.GetUninitializedObject()
but doesn't work in medium trust. 有一种使用
FormatterServices.GetUninitializedObject()
但在中等信任度下不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.