How to avoid double proxy constructs using DynamicProxy :: CreateClassProxyWithTarget?

I decorate an existing object with the CreateClassProxyWithTarget method. However, the constructor, and therefore the initialization code, is called twice. I already have a β€œbuilt” instance (target). I understand why this is happening, but is there a way to avoid this other than using an empty constructor?

Edit: Here is the code:

First create a proxy:

 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 now I call BindingFactory.Create(someKatalogBaseObject); Values and Attributes properties are initialized again.

+4
source share
2 answers

Based on one of Krzysztof's articles and his comment on the Moq forum, I managed to achieve this:

  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); } } 
+2
source

So what do you ask if DynamicProxy can build a proxy instance without calling its constructor?

This is not real. There is a method that uses FormatterServices.GetUninitializedObject() but does not work in the trust tool.

0
source

All Articles