Dynamic service endpoint binding for Silverlight using WCF

As part of my continuing effort in create a high quality line of business application in Silverlight, I am laying out a nice foundation for the repository layer. The services interaction is being shielded from the higher layers.

The main hurdle that was annoying me was having to change the endpoint the Silverlight application was pointing by editing a configuration file that was embedded in the application. Mainly, the fact that this required a recompile when going from local build to server. What a pain!!! Bad Microsoft…Bad..

I decided to just write a simple addition to my factory to generate the endpoints on the fly, no more recompile per site required. This also lets the application easily be moved server to server without any pains. Relative WCF URLS should have been a mandatory addition, but alas their not. If Microsoft had thought of everything, I wouldn’t have a job I guess.

Here is the simple code to do a dynamic endpoint in Silverlight. Enjoy!

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Windows;

namespace Seekford.Repository.MyServices
{
    internal class MyServiceFactory
    {
        private const string myServiceLocation = "../Services/MyCService.svc";

        /// <summary>
        /// Creates the binding.
        /// </summary>
        /// <returns></returns>
        private static CustomBinding CreateBinding()
        {
            CustomBinding binding = new CustomBinding();
            binding.Name = "SilverlightBindingGoodTimes";
           binding.Elements.Add(new BinaryMessageEncodingBindingElement());
            binding.Elements.Add(new HttpTransportBindingElement()
                {
                    MaxBufferSize = int.MaxValue,
                    MaxReceivedMessageSize = int.MaxValue
                }
            );

            binding.OpenTimeout = new TimeSpan(0, 5, 0);
            binding.CloseTimeout = new TimeSpan(0, 5, 0);
            binding.ReceiveTimeout = new TimeSpan(0, 5, 0);
            binding.SendTimeout = new TimeSpan(0, 5, 0);         

            return binding;
        }

        /// <summary>
        /// Creates the aand C service client.
        /// </summary>
        /// <returns></returns>
        public static MyServiceClient CreateMyServiceClient()
        {
            var binding = CreateBinding();
            return new MyServiceClient (binding, new EndpointAddress(
                new Uri(Application.Current.Host.Source, myServiceLocation )));
        }       

    }
}

You will obviously need to tailor to your needs, but the idea is pretty straight forward.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *