开发者

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

开发者 https://www.devze.com 2023-02-01 05:37 出处:网络
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 i

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 nh开发者_JS百科ibernate uses.)


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

精彩评论

暂无评论...
验证码 换一张
取 消