DynamicProxy rocks!
Recently, I've had a need to create proxy objects in two unrelated projects. What they had in common was that they both dealt with .NET Remoting. In one it was traditional Remoting between machines, in the other working with multiple AppDomains for Assembly flexibility. In both scenarios, I had a need for additional proxies other than the Remoting created Transparent proxy and the
Castle project's
DynamicProxy proved invaluable and versatile. It's a bit sparse on documentation, but for the most part, you should be able to figure things out by playing with it and lurking around their
forum.
If you're not familiar with the Castle project, check it out, because DynamicProxy is really only a supporting player in an excellent collection of useful tools. From their Inversion of Control Containers MicroKernel/Windsor to MonoRail and ActiveRecord (built on NHibernate), there is a lot there that can make your life easier.
But why would I need to create proxies, when the Remoting infrastructure in .NET takes care of this for you with Transparent Proxies? Well, let me describe both scenarios:
Resilient Client/Server operations with Remoting
From my experience with .NET Remoting, it's dead simple to do something simple. But it really is best suited for WebService stateless calls, because there isn't a whole lot exposed to add quality of service plumbing. The transparent proxy truly is transparent until something fails. Same is true on the server side, where you don't get a lot of insight into the clients connected to you.
And then there are events, which, imho, are one of the greatest thing about doing client/server programming with Remoting. Those are painful in two ways, having to have a MarshalByRefObject helper proxy the event calls and pruning dead clients on the server which you won't find out about until you try to invoke their event handler.
But those shortcomings are not enough reason to fall back to sockets and custom/stateful wire protocols. Instead I like to wrap my transparent proxy in another proxy that has all the plumbing for maintaining the connection, pinging the server and intelligently handling failure. Originally I created them by hand, but I just converted my codebase over to use DynamicProxy the other day.
Using CreateInterfaceProxyWithoutTarget and having the proxy derive from my plumbing baseclass automagically provides me with an object that looks like my target interface by wraps the Remoting proxy with my quality of service code.
public static RemotingClient<T> GetClient(Uri uri)
{
Type t = typeof(T);
ProxyGenerator g = new ProxyGenerator();
ProxyGenerationOptions options = new ProxyGenerationOptions();
options.BaseTypeForInterfaceProxy = typeof(RemotingClient<T>);
RemotingClient<T> proxy =
(RemotingClient<T>)g.CreateInterfaceProxyWithoutTarget(
t, new Type[0], options, new ProxyInterceptor<T>());
proxy.Uri = uri;
return proxy;
}
I'll do another post later just on Remoting, since the whole business of getting events to work was a bit of a labor and isn't documented that well.
Loading and unloading Assemblies on the fly
The second project started with wanting to be able to load and unload plug-ins dynamically and has now devolved into a framework for auto-updating components of an App at runtime.
This involves loading the assemblies providing the dynamic components into new AppDomains, so that we can unload the assemblies again by unloading the AppDomain. Instances of the components class are then marshaled across the AppDomain boundary by reference so that the main AppDomain never loads the dynamic assembly. This way, when a component needs to be updated, I can dump that AppDomain and recreate it.
The resilience of the connection isn't in question here, although there is need for quite a bit of plumbing to get references to the remoted components disposed before the AppDomain can be unloaded. Again, a DynamicProxy can help on the main AppDomain side by acting as a facade to the actual reference, so that you can reload the underlying assembly and recreate the reference without the main application having to be aware of it.
But I haven't gotten that far, nor have I decided whether that would be the best way, rather than an explicit disposal and recreation of the references.
Where DynamicProxy comes to a rescue here is when your object to be passed across the boundary isn't derived from MarshalByRefObject. This could be a scenario, where you are trying to use a component that's already derived from another baseclass, so adding MarshalByRefObjectisn't an option. Now DynamicProxy with its ability to provide a baseclass for the proxy gives you a sort of virtual multiple inheritance.
This is also an ideal scenario for using Castle.Windsor as the provider of the component. Using IoC, I was able to create a generic common dll that contains all the interfaces as well as a utility class for managing the components that need to be passed across the boundary, this class never has to know anything about the dynamic assembly, other than that the assembly stuffs its components into the AppDomain's Windsor container.
The resulting logic for creating an instance that can be marshaled across AppDomain boundaries looks something like this:
public T GetInstance<T>()
{
Type t = typeof(T);
if (!t.IsInterface)
{
throw new ArgumentException("Type must be an interface");
}
try
{
T instance = container.Resolve<T>();
if (typeof(MarshalByRefObject).IsAssignableFrom(instance.GetType()))
{
return instance;
}
else
{
ProxyGenerator generator = new ProxyGenerator();
ProxyGenerationOptions generatorOptions = new ProxyGenerationOptions();
generatorOptions.BaseTypeForInterfaceProxy = typeof(MarshalByRefObject);
return (T)generator.CreateInterfaceProxyWithTarget(t, instance, generatorOptions);
}
}
catch (Castle.MicroKernel.ComponentNotFoundException)
{
return default(T);
}
}
All in all, DynamicProxy is something that really should be part of the .NET framework. Proxying and Facading patterns are just too common to only support them via the heavier and MarshalByRefObject dependent remoting infrastructure.
The version of DynamicProxy I was using was DynamicProxy2, which is part of the Castle 1.0 RC3 install. It's a lot more versatile than the first DynamicProxy and deals with generics, but mix-ins are not yet implemented in this version. However, if you just need a single mix-in, specifying the base class for your proxy can go a long way to solving that limitation.
Labels: AppDomain, Castle, Dynamic Proxy, IoC, Remoting
INotifyPropertyChanged and Cross-thread exceptions
I'm currently reading
Adam Nathan's
WPF Unleashed. It's a good read and has me ready for doing some serious WPF work. However, the things I have on my plate are a already Windows Forms and can't really take a late in the project UI architecture change, so my production use of WPF will have to wait a little longer. I originally thought WPF was horribly over-engineered, but going through Adam's book, the decisions that led to the sometimes odd APIs make sense. It's clear that toolability of Xaml, separation of logic and code and allowing the greatest amount of design without any code are what led to the cumbersome manual C# syntax. But once you mix in Expression Blend, you won't be doing any of those nasty things unless you're writing your own custom controls. Ok, this is a lovely tangent, but hardly the subject of this entry...
While reading I came across INotifyPropertyChanged. Since it's meant for binding in general, I thought this might be a perfect fit for a design issue I was having on a WinForms project. Basically, I have an object that manages a native process and can get manipulated via remoting. The UI in the program really just exists for status updates on this management object. The solution for keeping the UI in sync was either a timer that polled the object's properties or create an event for each property change, manually subscribe to them in the form and update the UI that way. However, INotifyPropertyChanged provided a simple methodology for tracking changes in all objects and let the implementing object be used for data-binding. I'm usually against code that uses strings to reference object members, like data-binding is wont to do, since it falls outside of compile-time checking and is liable to get out of sync in refactoring, but data-binding is convenient and so prevalent in .NET, that I decided to use it for this.
Implementing INotifyPropertyChanged on my object was dead simple and the syntax for binding my labels to property changes was even easier. Perfect, another process simplified. Or so I thought. What happened next is what I personally would describe as a bug or at least mis-feature in data binding, but at least according to the docs, it's by design.
INotifyPropertyChangeddoes not work for asynchronous operations
What happened was this: I made changes to my object via the remoting proxy and my client UI died with an InvalidOperationException(Cross-thread operation not valid...). On it's face this is straight forward: My object is on a background thread, being manipulated by remoting. My UI is on the UI thread, so tweaking the UI by the background thread is a no-no. This is confirmed by the MSDN documentation which says:
If your data source implements the INotifyPropertyChanged and you are performing asynchronous operations you should not make changes to the data source on a background thread. Instead, you should read the data on a background thread and merge the data into a list on the UI thread.
That to me is bad advice and a lazy way of saying that data binding doesn't do its due diligence on binding operations. Why? Well, the purpose of something like INotifyPropertyChanged is Separation of Concerns, decoupling the observer of the property data from the observable object. But what the above says is that the observed object is responsible for knowing how it might be observed.
The logical thing is that your INotifyPropertyChanged object neither knows nor should care that it's data may be used to update the UI on another thread. The party that's responsible for that bit of house-keeping is the one that does the actual updating of the UI controls, i.e. data-binding. Data-binding is intimately aware of the UI object it's tied to and it's the one that isactually updating the UI in response to an incoming event. It seems logical and practical that it would do the necessary check on Control.InvokeRequired and perform said invoke. Instead telling you that your object better live on the UI thread is just not very good advice, imho.
Where does that leave us?
Well, even if the business object wanted to invoke on the UI thread, it couldn't unless it was aware of the UI thread, and that once again violates the Separation of Concerns that should exist between business logic and UI. So that leaves us with two options: a) change the way binding works to the way described above or b) put a proxy between the binding and the INotifyPropertyChanged implementor.
Since you can assign a new BindingContext to a control, a) may be an option, and it's one I'm going to investigate next. However for the time being, going down the path of b) was simpler.
I hardcoded a proxy for my business object, had it implement INotifyPropertyChanged as well and created a factory that would take both the form and the proxied object to create a new proxy. The proxy then subscribed to the proxied PropertyChanged event and used its reference to the form to make sure it was invoked on the UI thread.
public class MyBusinessObject : INotifyPropertyChanged
{
[...]
public int MyProperty
{
get { [...] }
}
[...]
}
public class MyBusinessObjectProxy : INotifyPropertyChanged
{
Control bindingControl;
MyBusinessObject bindingSource;
private MyBusinessObjectProxy(Control bindingControl, MyBusinessObject bindingSource)
{
this.bindingControl = bindingControl;
this.bindingSource = bindingSource;
bindingSource.PropertyChanged += new PropertyChangedEventHandler(bindingSource_PropertyChanged);
}
void bindingSource_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
if (bindingControl.InvokeRequired)
{
bindingControl.BeginInvoke(new PropertyChangedEventHandler(bindingSource_PropertyChanged), sender, e);
return;
}
PropertyChanged(this, new PropertyChangedEventArgs(e.PropertyName));
}
}
public int MyProperty
{
get { return bindingSource.MyProperty; }
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
That works beautifully, but since it's specific to my particular object that's a lot of hand-coding. This whole proxy/adapter scheme screams for a generic implementation. But now we need to intercept requests of properties we may not know exist. Back in the perl days (and most dynamic languages feature this as well) I would have just created an AUTOLOAD method that catches all calls to methods that don't exist. It didn't seem like this would exist in C#, since that violates the whole compile time checking of a static language like C#. But there is Reflection, so maybe I was wrong. However, after checking with Oren Eini, who clearly has a much greater understanding of how to do funky things with C#, it turns out that such a facility indeed does not exist.
Next up was creating a proxy object that could be cast to the original type and handle the binding calls that way. I built a prototype based on Castle's Dynamic Proxy, which proxied the properties just fine, but apparently the event subscription doesn't work, because the proxy's PropertyChanged event never acquired any subscribers. So until I can figure out what happens to events on Dynamic Proxy, I'm stuck with statically built proxies.
In the meantime, I guess I'm going to look at BindingContext to see if the problem can be solved generically at that end, while trying to figure out why Dynamic Proxy isn't working. Stay tuned.
Labels: .net, c#, Castle, cross-thread exception, Data Binding, Dynamic Proxy, INotifyPropertyChanged