问题
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