This post is part of a series about WCF extensibility points. For a list of all previous posts and planned future ones, go to the index page.
And we’re reaching the end of this series. To close it, I’ll cover some of the lesser used extensibility points in WCF, which would be too short for a full post. This time I’ll cover the “initializer” interfaces, which can be used to, well, initialize some component of the WCF runtime. Those are the IInstanceContextInitializer, ICallContextInitializer and IChannelInitializer, which will be covered in detail below.
And since there will be multiple samples in this post, the usual disclaimer goes ahead: they are simple samples for illustrating the topics of this post, not production-ready code. I tested them for a few contracts and they worked, but I cannot guarantee that they will work for all scenarios – please let me know if you find a bug or something missing. There are some shortcuts I did in them to make the sample smaller, such as not using real resource files in the call context initializer sample, and, as usual, error checking has been kept to a minimum.
The example from the previous post showed how we can completely control the instance context life cycle with the IInstanceContextProvider interface. There are some scenarios, however, where all we want is to simply perform some initialization code when a new instance context is created – essentially, only implement the InitializeInstanceContext method in the instance context provider. Such scenarios can involve attaching an extension to the instance context, or possibly doing some custom throttling. For those cases, having to implement the whole instance context provider is a lot of work, so for this scenario WCF also provides (yet) another extensibility point, the IInstanceContextInitializer interface, which is called whenever a new instance context is created. The interface declaration is shown below.
The Initialize method in the instance context initializer is called when a new instance context is created. If there is a custom instance context provider, the provider’s InitializeInstanceContext method will be called first, then all of the initializers in the dispatch runtime will be called.
To add an instance context initializer to the WCF runtime, you need to add it to the InstanceContextInitializers property in the DispatchRuntime object. They’re typically added in endpoint or service behaviors, as shown in the example below.
And that’s probably all you need to know about instance context initializers.
Just like the instance context initializer, the channel initializer can be used to perform some initialization on channels. The IChannelInitializer, however, can be used both at the client and at the server side. At the former, it’s called either when CreateChannel is called on a channel factory (directly or indirectly via a class derived from ClientBase<TChannel>). At the latter it’s called when a new session is created (for session-less bindings, that’s essentially for every new request). Channel initializers are usually used to track existing client sessions. The interface definition is shown below.
The Initialize method on the channel initializer is called when a new channel is created, and unlike the instance context initializer, it isn’t given the message (on the client there isn’t such a message when the channel is initialized), only the client channel which has been created. Applications will typically add a listener to the channel’s Closed (or Closing) event to know when the channel is being recycled.
Channel initializers on the server are bound to the ChannelDispatcher object, and typically accessed in endpoint behaviors. On the client side they’re bound to the ClientRuntime object directly, and also typically accessed in endpoint behaviors, as shown in the code below.
Real world scenario: tracking session objects and detecting client disconnection
I’ve found this question in the MSDN forums and in some other places as well: how to determine when a client disconnected from a (session-full) service? As the answerer for that post suggested, the channel initializer is a good option for that. On the initializer we can register to the closed event on the channel, which will be called when the client disconnects (i.e., closes the channel).
For this sample I chose the same contract as in the post about instance context providers, but this time we’ll use a real session-full binding instead of having all the trouble of creating a custom provider (this sample is about channel initializers after all).
This time the server will not only trace the operations which are happening, but also the number of clients which are connected at a given time, with that information coming from our channel initializer class.
The channel initializer itself will just count the number of clients connected at a given time. When a new channel is created, the Initialize method is called and the code increments the counter. It then starts listening to both Closed and Faulted events on the channel, so that if the client disconnects gracefully or not the code will be notified, so that the counter can be decremented.
To set up the channel initializer, an endpoint behavior:
And to test the implementation, we create two client channels and connect both to the service. When we close the first, the Closed event is fired and the tracker decrements the number of connected clients at the server.
And that’s it for the channel initializer.
The last of the initializer interfaces is not about initializing any of the WCF runtime objects, but the context in which the service operation will be executed. And by context it just means the thread – this is the interface which lets the implementer to set any thread-local variables which can be used by the service operations as they’re executed – thanks to the authors of this post about this interface, since I had never used it before, for helping me find out its usage. Any properties of the Thread class, such as the current [UI] culture, impersonation (current principal), or any other variables marked with ThreadStaticAttribute are a good candidate for initialization by this extensibility point, whose interface is shown below.
When an incoming request arrives, after the instance provider hands WCF the service instance to be used, BeforeInvoke is called so that the initializer can, well, initialize the context of the call. The context is preserved throughout some of the runtime components, including the dispatch message formatter, any parameter inspectors and the operation invoker. The method returns an object, the correlation state, which will be passed to the AfterInvoke method, which is called after the same components (invoker, parameter inspector, formatter). It’s on AfterInvoke that the initializer will typically restore the state of the thread to what it was before the BeforeInvoke call.
To add a call context initializer to the WCF runtime, you need to add it to the CallContextInitializers property of the DispatchOperation object. This is typically done either inside an operation or an endpoint behavior, as shown in the example below.
Real world scenario: supporting Accept-Language header in requests
This is one of the cases where a call context initializer can be useful. By binding the HTTP Accept-Language header to the thread culture, we can use the resource management libraries in .NET to load strings from the culture expected by the client. This is a simple application that does that. The service is very simple, with a single operation which takes three parameters and return a Person object. The constructor of that class may throw an exception if any of the parameters is invalid, and we’ll wrap that in a WebFaultException to return the message to the client.
The exception message is retrieved from a simulated resource manager (I didn’t find out quickly how to have multiple resource languages in a VS project to enable a quick F5 experience, and since it wasn’t overly relevant to the topic I decided to have a mock one).
In order to add the call context initializer to the runtime, I used an endpoint behavior in this sample, as shown below.
The call context initializer itself is shown below. During BeforeInvoke, the code looks at the HttpRequestMessageProperty from the request to see if it has an Accept-Language header. If it does, it will try to get a CultureInfo object from the value of the header (notice that this implementation doesn’t handle ‘q’ values or multiple languages), and set it to the CurrentCulture property of the current thread. On the AfterInvoke method, the initializer restores the original culture.
To test it we can host the service, add an endpoint and add the appropriate behavior. In this case, since we’re using a HTTP endpoint, we add both the WebHttpBehavior (to make it a Web HTTP endpoint) and our GlobAwareEndpointBehavior, which will add the call context initializer. Then we send a few requests, one which should succeed, and one for each possible error message which the service can return.
And that’s it for the last of the initializers.