加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何避免使用DynamicProxy :: CreateClassProxyWithTarget

发布时间:2020-12-15 17:27:03 所属栏目:百科 来源:网络整理
导读:我正在使用CreateClassProxyWithTarget方法装饰现有对象.但是,构造函数和初始化代码被调用两次.我已经有了一个“构造的”实例(目标).我理解为什么会发生这种情况,但除了使用空构造函数之外,有没有办法避免它? 编辑:这是一些代码: 首先是代理创建: public
我正在使用CreateClassProxyWithTarget方法装饰现有对象.但是,构造函数和初始化代码被调用两次.我已经有了一个“构造的”实例(目标).我理解为什么会发生这种情况,但除了使用空构造函数之外,有没有办法避免它?

编辑:这是一些代码:

首先是代理创建:

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;
}

我使用它作为例如以下类的对象:

public class KatalogBase : AuditableBaseEntity
{
   public KatalogBase()
   {
     Values     = new HashedSet<Values>();
     Attributes = new HashedSet<Attributes>();
   }
   ...
}

如果我现在调用BindingFactory.Create(someKatalogBaSEObject);价值观和属性
属性再次初始化.

解决方法

在Moq论坛上以 one of Krzysztof’s articles和他的 comment为基础,我设法让这个工作:

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);
        }


    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读