My recipe for WCF part 3 – Rolling your own integration with an IoC

It’s been a while since I last posted about WCF. In the meantime I’ve been doing a Coursera course on Computational Investment. I must say that I don’t feel much better qualified to start a hedge fund as a result – it all seems a little too simple, and I’m sure that transaction charges would push any trading algorithm I could devise into negative returns. I have, however, adopted the sophisticated investment strategy of buying Royal Mail shares in the IPO. My husband and I decided to hedge against an undervaluation by purchasing approximately the stake we already own (about £1000 between us based on a market capitalisation of £3.3bn and a UK population of 70million) We got £750, as did all retail investors except those enthusiastic enough to have applied for over £10K’s worth who were rewarded with no shares at all.

I’ve made some improvements to the algorithm: following a discussion with a mathematician, I’ve used a Discrete Fourier Transform method for multiplying polynomials. This has reduced the time needed to test all primes less than 100000 down from about a week to about an hour. It’s still quite slow though and really I’ve come to the conclusion that .NET isn’t suitable for doing calculations with large numbers. One of the problems is that BigInteger is a value type, which means that every time you assign it to a variable or pass it to a method a copy is made. At one point I made multiplication run 10 times more slowly by doing something like

BigInteger b = a[0];

i.e. assigning a reference to a BigInteger in an array to a variable. It might be interesting to see if it were possible to wrap fast maths implemented in Iron Python or something in a .NET interface, though I’m not sure I can bear the prospect of implementing this particular algorithm again.

So! Let’s get to the WCF programming point of this post. I’m showing how to get an IoC library to manage the creation of the proxy classes when using WCF. I used StructureMap because it doesn’t come with a pre-packaged library for doing this. There isn’t that much code to write on the client side: it’s only necessary to register the Channel Factories as singletons:

For<ChannelFactory<IPrimeTester>>()
                .Singleton()
                .Use(new ChannelFactory<IPrimeTester>(
                           new BasicHttpBinding("defaultBinding"),
                           GetServiceAddress("PrimeTester.svc")));
        }

and then to register the proxy interfaces themselves as being created by these ChannelFactories:

For<IHcfService>()
                .Transient()
                .Use(() =>
                    {
                        var channelFactory = 
                            ObjectFactory.GetInstance<ChannelFactory<IHcfService>>();
                        return channelFactory.CreateChannel();
                    });

The full code of the class which is used to register the client side proxies is below.

using System.ServiceModel;
using CalculatorServiceInterfaces;
using StructureMap;
using StructureMap.Configuration.DSL;

namespace Calculator.StructureMapConfig
{
    public class WcfRegistry : Registry
    {
        public WcfRegistry()
        {
            RegisterChannelFactories();
            RegisterChannels();
        }

        private void RegisterChannels()
        {
            For<IHcfService>()
                .Transient()
                .Use(() =>
                    {
                        var channelFactory = ObjectFactory.GetInstance<ChannelFactory<IHcfService>>();
                        return channelFactory.CreateChannel();
                    });

            For<IPrimeTester>()
                .Transient()
                .Use(() =>
                    {
                        var channelFactory = ObjectFactory.GetInstance<ChannelFactory<IPrimeTester>>();
                        return channelFactory.CreateChannel();
                    });
        }

        private void RegisterChannelFactories()
        {
            For<ChannelFactory<IHcfService>>()
                .Singleton()
                .Use(new ChannelFactory<IHcfService>(new BasicHttpBinding("defaultBinding"),
                                                     GetServiceAddress("HcfService.svc")));
            For<ChannelFactory<IPrimeTester>>()
                .Singleton()
                .Use(new ChannelFactory<IPrimeTester>(new BasicHttpBinding("defaultBinding"),
                                                      GetServiceAddress("PrimeTester.svc")));
        }

        private string GetServiceAddress(string serviceName)
        {
            return ObjectFactory.GetInstance<AppSettings>().ServiceBaseUrl + serviceName;
        }
    }
}

On the server side there’s not really anything that I can add to this blog post, which tells you exactly what to do, so I won’t try. I have, however, taken the code in that post and put it into a separate project with an output to a Nuget package, so if you want to use it you won’t have to write it yourself.

If you want to see all the code, fully loaded with Fourier Transforms and StructureMap, take a look here.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s