Friday, December 4, 2009

WPF and NHibernate Lazy Proxies

Using NHibernate proxies with WPF binding will likely leave you scratching your head at moments. There are at least two issues that can get in your way. The first of these is that objects with INotifyPropertyChanged implementations will not update when the property is changed. Even though the event is fired, the WPF value never updates itself. This is because WPF compares the source of the event against the object that it originally registered the event with. Since the source of the event is the actual implementation object hidden by the proxy, but the object WPF knows about is the proxy object, WPF ignores the event. The best way to fix this is to have the proxy object rewrite the property changed events. There is a detailed explanation and a simple implementation here, but be aware that it doesn't redirect events from the source but throws its own events when properties are set. The other issue you will sometimes run into is a strange null reference exception when setting the value of a dependency property. There is a bug in WPF where it doesn't properly handle the names of classes without any namespaces. Since the lazy proxy objects have no namespace, this bug pops up. The issue is fixed in WPFv4, but if you aren't able to upgrade, you can fix this by changing a line in Castle.DynamicProxy. In ClassProxyGenerator.GenerateCode, add the "Proxies." part to the following line: String newName = "Proxies." + targetType.Name + "Proxy" + Guid.NewGuid().ToString("N"); This should help anyone experiencing the error relating to DetermineWhetherDBNullIsValid.

No comments: