Tuesday, September 18, 2007

Wcf windows service host - adding services based onto configuration.


While coming to the bitter understanding that there is no really generic way how to add types to the windows service hosting based solely onto system.serviceModel configuration, I found the following from the master of .NET remoting Ingo Rammer:

Ingo Rammer's windows service host solution:
http://blogs.thinktecture.com/ingo/search.aspx?q=system.serviceModel&p=1

What I wanted though to change a bit on it, is to avoid a separate file for the configuration and avoid a bit of extra code for this file structure.

A bit different solution that requires less code and doesn't need a separate configuration file:

In the configuration file add an extra section

<section name="Dsi.ServiceModelHost" type="System.Configuration.NameValueSectionHandler, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

Section name is up to your choice, so far nothing not located in the .NET is used as System.Configuration.NameValueSectionHandler is just a standard handler that processes the section of a form:

<Dsi.ServiceModelHost>
  <add key="Dsi.Tools.ServiceHost.Wcf.HostedServicesEnumerator"
       value="Dsi.Tools.ServiceHost.Wcf.HostedServicesEnumerator, Dsi.Tools.ServiceHost.Wcf" />
</Dsi.ServiceModelHost>

Where the key in our sample will be a service name, same as used in the name attribute of the service element (though not required at all, but makes sense), value points to the fully qualified type name.

Then the code would resemble something like:

NameValueCollection servicesConfig =
    (NameValueCollection)ConfigurationManager.GetSection(
    "Dsi.ServiceModelHost");

foreach (string serviceName in servicesConfig.Keys)
{
    Contracts.Add(Type.GetType(servicesConfig[serviceName]));
}

Add more exception handling/instrumentation according to your choice of utensils and this should be basically it.

Only adding those snippets here as our code is far more complicated :).

Technorati Tags: ,
Post a Comment