Monday, 17 January 2011

Quick explanation of generating dynamic WCF client proxies with Unity;

I’ve been using castle windsor for years now and it’s been my favourite IOC and DI container for a long time. On one of my current projects, I’ve been forced to look at Unity a bit more closely and the first thing that came up for me was how to create WCF client proxies automatically from the shared service contracts. This is how I did it;

I configure the container with code at the moment – I don’t know about you but the usefulness of IOC isn’t the fact that you can replace components at runtime, it’s the clean separation and testability that following a loose coupled pattern gives you. So, I configure my container in code – if I needed the ability to replace bits later, I’d devolve just that part of the configuration out to XML or such like, but I wouldn’t start at XML – it’s too easy to introduce a typo and it doesn’t support refactoring easily.

Anyway, so the complexity of registering a WCF client proxy is it doesn’t have a concrete implementation – I have an interface assembly that contains the service contracts and data contracts and I want to tell WCF to wrap the interface with a channel factory and create the resultant channel.

Unity provides a way of doing just that;

_host.RegisterType<TService>(new InjectionFactory(c => new ChannelFactory<TService>(endpointConfigurationName).CreateChannel()));

TService is our interface and endpointConfigurationName is the name of our endpoint configuration in app.config. What this does is when something wants to resolve an instance of TService, it calls the lambda contained within the injection factory and this in turn creates a channel around the interface.

As such, you can then just go ahead and call your interface members and it will wire everything up for you. No need for service references etc, it just works :)

No comments:

Post a Comment