Monday, January 16, 2012

Extracting WCF bindings

Couple days ago my colleague Rimas and me came across a situation where we needed to add several configuration parameters to some predefined WCF binding. We also wanted to know how those predefined bindings are configured. WCF provides many bindings preconfigured out of the box - starting with BasicHttpBinding moving all the way down to more complex configurations. All of them basically are Binding instances with some predefined set of configuration parameters which we were interested in.

One of the easiest ways to see what's inside the binding is to add a service reference using Visual Studio. It  generates a proxy class and configures client to use the service so the binding information gets pushed into *.config file.

Generating configuration parameters for all WCF bindings at once is a bit more complex task. We solved it this way:

static void Main(string[] args)
{
    string sectionName;
    string configName;

    var types = Assembly.Load("System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
        .GetTypes()
        .Where(t => t.IsSubclassOf(typeof(System.ServiceModel.Channels.Binding)))
        .Where(t => !t.IsAbstract)
        .Where(t => t.GetConstructor(Type.EmptyTypes) != null)
        .ToArray<Type>(); 

    var generator = new ServiceContractGenerator(
        ConfigurationManager.OpenMappedExeConfiguration(
            new ExeConfigurationFileMap() { ExeConfigFilename = "Bindings.config" }, 
            ConfigurationUserLevel.None));

    foreach (var type in types)
    {
        generator.GenerateBinding(Activator.CreateInstance(type) as System.ServiceModel.Channels.Binding, out sectionName, out configName); 
    }

    generator.Configuration.Save(); 
}

No comments:

Post a Comment