Manual Context Management

How do I manually manage the context when sharing a client object?

The default mode when using a context binding is for the context to be managed internally by the context channel underneath the client proxy. This is similar to how by default cookies are managed by an HTTP channel to send and receive cookie context. With an HTTP channel you can disable automatic cookie management and control the context yourself. There is a similar process that you can use to take control for a context binding.

Here's a comparison of the two processes. You can get the code for HTTP by using the link above and with the further details on custom cookie handling so I won't print it again.

With HTTP, you first need to turn off automatic cookie handling by setting the AllowCookies property on the HTTP transport binding element to false.

With a context binding, you first need to turn off automatic context handling by setting the Enabled property on the context manager to false.

 IContextManager contextManager = channel.GetProperty<IContextManager>();
contextManager.Enabled = false;

Then, for HTTP you attach an HttpRequestMessageProperty that contains the desired cookies to a message using an OperationContextScope.

With a context binding, you use the same OperationContextScope approach but attach the appropriate ContextMessageProperty instead.

 using (new OperationContextScope(client.InnerChannel))
{
   ContextMessageProperty contextProperty = new ContextMessageProperty(contextData);
   OperationContext.Current.OutgoingMessageProperties[ContextMessageProperty.Name] = contextProperty;
   client.DoOperation();
}

Next time: Messaging Additions in Orcas