In my previous post I gave some examples of how Unity implements behaviours (or interceptors) typically using a form of the Decorator pattern. Most of the examples you see of where you use these behaviours are for classes you yourself own, and thus can put attributes on the methods or whatnot.
There is, however, another time where Unity’s behaviour / interceptor functionality is extremely useful, and that’s when you don’t have control over the class that you wish to decorate.
A good example of this is if, for example, you have a proxy WCF service reference in a client application. WCF will generate you a service class with all the methods from the WSDL file (and also generate the entities if you aren’t providing them yourself), and even generate an interface from that service class. However, it’s a generated file, subject to change at any time etc.. The interface is not partial and not really open for modification.
Caching a WCF service call
Let’s say that you want to implement some form of caching from your service proxy, so that if you call the same method twice, you don’t go back to the server the second time. Perhaps this is because the service method is static data or something. Yes, you could optionally provide a client-side class which caches the data manually, but now you’ve got two sources of data – one for static data and one for other “live” data. Wouldn’t it be nice if your service class offered caching for those methods that you want to cache data from, but not from the others?
In this case, the real problem is, of course, that the proxy class is generated so you can’t modify it at all – but this is when Unity comes in. Imagine the following proxy interface: –
The first three methods are typically reference data and shouldn’t be called more than once by the client application. The last two represent calls whose results are more dynamic and shouldn’t be cached.
Here’s a (mock) concrete implementation of the proxy. Remember, this code represents designer-generated code which we cannot modify: –
This mock class is set up so that the second call to any of the reference data methods throws an exception – obviously not exactly “real world” but it serves the purpose here to test if we will only certain methods more than once.
Here’s the code to simulate our client application: –
The Initialise method simply registers the ServiceProxy with the associated interface, and assigns it as a singleton – thus all calls to get IServiceProxy throughout the application would get the same proxy class.
The LoadSomeData method simply runs through the different methods and prints some data to the console.
Unsurprisingly, when we first run it, we get the following: –
So, how can we inject some caching into our proxy class without modifying it? That’ll be in my next post