微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何避免使用DynamicProxy :: CreateClassProxyWithTarget双重构造代理?

@H_502_2@
我正在使用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);价值观和属性
属性再次初始化.

@H_502_2@

解决方法

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


    }
@H_502_2@ @H_502_2@
@H_502_2@
@H_502_2@

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐