WCF to messaging bridge

Component: WCF Support
NuGet Package NServiceBus.Wcf (1.x)
Target NServiceBus Version: 6.x

This sample demonstrates how the WCF component can be leveraged to achieve reliable WCF services by bridging the WCF calls over messaging.

Running the project

  1. Start the projects by hitting F5.
  2. The text Press <enter> to send a message and Press <escape> to send a message which will time out should be displayed in the Client's console window.
  3. Hit enter to send a message or escape to send a message which will time out.

Verifying that the sample works correctly

  • When a message was sent with enter Response 'Hello from handler' will be displayed
  • When a message was sent with escape Request failed due to: 'The request was cancelled after 00:00:05 because no response was received.' will be displayed

Code walk-through

The sample contains a self-hosted endpoint that leverages the WCF and the Callbacks package to enable reliable WCF services over messaging.

The WCF) and the Callback component are enabled. The WCF component is configured to cancel requests after five seconds and a named pipe binding is used to expose the service as shown below:

endpointConfiguration.MakeInstanceUniquelyAddressable("1");
endpointConfiguration.EnableCallbacks();

var wcf = endpointConfiguration.Wcf();
wcf.Binding(
    provider: type =>
    {
        return new BindingConfiguration(
            binding: new NetNamedPipeBinding(),
            address: new Uri("net.pipe://localhost/MyService"));
    });
wcf.CancelAfter(
    provider: type =>
    {
        return type.IsAssignableFrom(typeof(MyService))
            ? TimeSpan.FromSeconds(5)
            : TimeSpan.FromSeconds(60);
    });

A channel factory is used to create a channel to communicate with the locally exposed WCF service

var pipeFactory = new ChannelFactory<IWcfService<MyRequestMessage, MyResponseMessage>>(
    binding: new NetNamedPipeBinding(),
    remoteAddress: new EndpointAddress("net.pipe://localhost/MyService"));
var pipeProxy = pipeFactory.CreateChannel();

The request message is passed to the proxy as shown below

var request = new MyRequestMessage
{
    Info = key.Key == ConsoleKey.Enter
        ? "Hello from handler"
        : "Cancel"
};
var response = await pipeProxy.Process(request)
    .ConfigureAwait(false);

The proxy will asynchronously wait until the response or the cancellation is received. A response is sent from a regular handler hosted in the same endpoint

public class MyRequestMessageHandler :
    IHandleMessages<MyRequestMessage>
{
    public Task Handle(MyRequestMessage message, IMessageHandlerContext context)
    {
        if (message.Info == "Cancel")
        {
            return Task.CompletedTask;
        }
        var response = new MyResponseMessage
        {
            Info = message.Info
        };
        return context.Reply(response);
    }
}

Related Articles


Last modified