Implementing IDataErrorInfo using Castle.DynamicProxy in lazy loading scenario using NHibernate

僤鯓⒐⒋嵵緔 提交于 2020-01-04 14:20:35

问题


I have implemented IDataErrorInfo interface using Castle.DynamicProxy IIterceptor. I have also implemented a NHibernate interceptor which instantiates my entities using this interceptor. The problem is with lazy loaded entities. These are constructed using a proxy factory class specified in nhibernate config file, which obviously does not provide IDataErrorInfo implementation. This proxies are masking the underlying implementation of IDataErrorInfo by my interceptor which causes the validation to fail.

What are the posible solutions of this problem?

(One way to solve the problem would be to change the default proxy factory which nhibernate uses.)


回答1:


One solution is to override the default Castle proxy factory and extend the interfaces array with IDataErrorInfo. The LazyInitializer does not actualy implement this interface, it only forwards calls to our own proxy implementation. The DataBindingProxyFactory must then be registered as NHibernate proxy factory.

 public class DataBindingProxyFactory : ProxyFactory, IProxyFactoryFactory
  {
    public IProxyValidator ProxyValidator { get { return new DynProxyTypeValidator(); } }

    public IProxyFactory BuildProxyFactory()
    {
      return new DataBindingProxyFactory();
    }

    public bool IsInstrumented(Type entityClass)
    {
      return true;
    }

    public override INHibernateProxy GetProxy(object id, ISessionImplementor session)
    {
      try
      {
        var initializer = new LazyInitializer(EntityName, PersistentClass, id, GetIdentifierMethod,
          SetIdentifierMethod, ComponentIdType, session);

        var interfaces =
          new List<Type>(Interfaces){
            typeof (INotifyPropertyChanged),
            typeof (IDataErrorInfo)
          }.ToArray();

        var generatedProxy = IsClassProxy
          ? DefaultProxyGenerator.CreateClassProxy(PersistentClass, interfaces, initializer)
          : DefaultProxyGenerator.CreateInterfaceProxyWithoutTarget(Interfaces[0], interfaces,
            initializer);

        initializer._constructed = true;
        return (INHibernateProxy) generatedProxy;
      }
      catch (Exception e)
      {
        log.Error("Creating a proxy instance failed", e);
        throw new HibernateException("Creating a proxy instance failed", e);
      }
    }
  }


来源:https://stackoverflow.com/questions/4525046/implementing-idataerrorinfo-using-castle-dynamicproxy-in-lazy-loading-scenario-u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!