Contents tagged with WCF

  • Registering a file-less WCF Service Dynamically

     I know...  I know...   it has been a while since my last post, but I never forgot about it, just having a blast doing some fun things. Well, some of that stuff wasn't really THAT fun, but that's part of being a CTO and always there is room for improvement in some processes and structures in the company, and so...  after a lot of hard work, we are now in a much better position to actually start doing some fun stuff.

    And the fun part has begun, in thre form of a couple new and REALLY interesting and fun projects, where I participate not only as CTO but also I'm fulfilling a role of an Chief Architect as well, overseeing aspects of general architecture from development and infrastructure standpoints, and more important, doing a LOT of research and proof of concepts to hand over to our Architect Team.

    So, for this new project (let's say, Codename "E2") I'm in charge of researching some stuff, and here I will present the results of one of those topics: dynamic (runtime) registering of WCF services.

    Before jumping in today's topic, let me talk a little about the other topics I'm researching, just to paint a broader picture and set the stage for future posts. Our E2 project is a little ambitious in some aspects, and it's main motto is "Configurable Dynamic", so we are exploring ways to make this happen and the list of things to explore first are:

    • Dynamic registration of WCF services (today's topic)
    • Dynamic Data Access (ORM without Entities)
    • Dynamic Business Rules (or logic, if you want)
    • Dynamic Business Processes (workflows are a possibility here, but not the only one)
    • Performance of of the above (mainly IIS, ASP.NET, WCF) and how to optimize the platform.
    • Performance techniques to use: caching, profiling, monitoring, etc.

     Of course there are other topics (like Security, Scalability, Fault Tolerance, etc) but we will advance over those in time. For today's topic, let's explain a little what I'm talking about. For WWCF services there are two ways of let know the runtime environment that we have a Service class and we want to expose it to the world:

    1. The plain old .svc file approach: we need a file with .svc extension and this file will contain the Type information needed to activate the service.
    2. The new CBA (configuration based activation) approach: this is new in NET4, and therefore is possible to create a WCF service WITHOUT the svc file, using only a section in the web.config file (<serviceHostingEnvironment><serviceActivations>).

    While this second option is very interesting, we cannot do it at runtime and so the idea of this post was born. We can register HttpModules at runtime (the MVC3 project do that to register the HttpModule that handles Razor views) and so wwe can try to do something similar. That functionality (dynamically register an HttpModule) could be found in the "Microsoft.Web.Infrastructure" assembly using the "RegisterModule" method found in the "DynamicModuleUtility" class.

    We are going to take a similar approach to this helper method and use reflection to inject our service configuration somewhere so the runtime thinks it have a CBA Service (file-less) and can active it as any normal service. This is achieved in the "DynamicServiceHelper" class in the attached sample project, using the "RegisterService" method.

     This is the source code for the "RegisterService" class:  (some lines where removed for brevity)

    namespace System.ServiceModel
        public static class DynamicServiceHelper
            static object _syncRoot = new object();
            static FieldInfo hostingManagerField;
            static MethodInfo ensureInitialized;
            static FieldInfo serviceActivationsField;
            static DynamicServiceHelper()
                ensureInitialized = typeof(ServiceHostingEnvironment).GetMethod("EnsureInitialized"BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod);
                hostingManagerField = typeof(ServiceHostingEnvironment).GetField("hostingManager"BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.GetField);
            public static void EnsureInitialized()
                ensureInitialized.Invoke(nullnew object[] { });
            public static void RegisterService(string addr, Type factory, Type service)
                lock (_syncRoot)
                    object hostingManager = hostingManagerField.GetValue(null);
                    if (serviceActivationsField == null)
                        serviceActivationsField = hostingManager.GetType().GetField("serviceActivations"BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
                    Hashtable serviceActivations = (Hashtable)serviceActivationsField.GetValue(hostingManager);
                    string value = string.Format("{0}|{1}|{2}", addr, factory.AssemblyQualifiedName, service.AssemblyQualifiedName);
                    if (!serviceActivations.ContainsKey(addr))
                        serviceActivations.Add(addr, value);

    This class have two methods: "RegisterService" and "EnsureInitialized". The first method is pretty self explanatory, it receives the service activation information (endpoint, service type and factory type) but the "EnsureInitialized" method deserves a little explanation. As you can see, we use the "ServiceHostingEnvironment" class, and this class is used internally to manage all WCF services running in our process. It uses an internal class named "HostingManager" that is in charge of doing the discovery of existing WCF services (by looking for ".svc" files in the application folder and reading the <serviceActivations> configuration section, so by using a little reflection we can see that this information is processed in the private method "LoadConfigParameters", and in that method we see that the list of services to activate is added to the private field named "serviceActivations" (a Hashtable).

    If you see the example code, you would also see there is another class named "Startup" that contains an assembly attribute named "PreApplicationStartMethod":

    [assembly: PreApplicationStartMethod(typeof(WcfService1.Startup), "Init")]

     This attribute says to the runtime environment (WAS) that should call the "Init" method in the "Startup" class, and this method is called to give you the chance to initialize your code so it's called almost before anything else so the WCF / WAS infrastructure is not yet initialized at this point. So, in this moment we cannot use anything on the "ServiceHostingEnvironment" class. Hopefully, this class also have an "EnsureInitialized" method (private, of course) so we can try to invoke it and hope it doesn't have any other dependency and will initialize what wew need to register our service. Luckily for me, it worked without any evident side-effects, so let's use it!

    Another method to register our services would be not calling the "EnsureInitialize" method and wait for something else to do it. In that case we can create (and dynamically inject) an HttpModule to register our service in it's "Init" method. That will work and I'm including that code in my sample as well (in fact it was my first approach) but it has an important drawback: it needs to something else to initialize the Http stack, and therefore our WCF Service (using TCP to make things more interesting) will not be activated if the hosting application doesn't receive an Http request first.

    Well, that's it, hope you enjoyed the reading and find the code useful (by the way, you can use it in any way you want, so I have to include here the usual "No warranties" disclaimer), and if you make some improvement or have any comments about my code I would like to know.

    You can download the source code from here:

    Best regards,

    Andrés G Vettori, CTO, VMBC


  • White paper: understanding WCF extensibility

    I have written a white paper on WCF extensibility and I would like to share it with the community so I have attached a copy to this post in Word 2003 format.


    Andrés G Vettori, VMBC, CTO


  • WCF Extensibility - Part 2

    Service Description

     Service Description at Runtime

    Figure 2. ServiceDescription at runtime


    The Service Description is the heart of the service and is created when a ServiceHost or client ChannelFactory is created to describe all aspects of the service, endpoints and behaviors. This description is a logical view of what the WCF runtime is going to build when the Open method on the ServiceHost is executed, and also is used to generate the WSDL and policy metadata for the service. This metadata is exposed through the ServiceDescription class and the Description property on the ServiceHost and can be changed, for example, by injecting behaviors. To build the ServiceDescription information the WCF runtime first reflects over the service types and then it loads the service configuration. This information is then used when you execute the Open method of the ServiceHost to build the runtime.

    In the code shown below you can see how the service description information could be accessed and modified:


    // Construct the ServiceHost
    ServiceHost host = new ServiceHost(typeof(EchoService), new Uri(“http://localhost/echo”) );
    // Add endpoints to description
    host.AddServiceEndpoint(typeof(IEchoService), new BasicHttpBinding(), “”);
    // You can access the Description property of the host
    // And you can change things before calling Open
    foreach( ServiceEndpoint endpoint in host.Description.Endpoints )
             // Add My behavior to all Http endpoints
             If( endpoint.Uri.Scheme == “http” )
                     endpoint.Behaviors.Add( new MyHttpBehavior() );
    // Open the Host

    Next post: Building a Custom ServiceHost


    Andrés G Vettori
    EDS Top Gun - .NET Capability Architect

    Leader of the C# Community of the Microsoft Users Group Argentina