Getting Started
Architecture
NServiceBus
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring

Reliable WCF communication over messaging

Component: WCF Support
NuGet Package: NServiceBus.Wcf (3.x)
Target Version: NServiceBus 8.x

This sample shows how the NServiceBus.Wcf package may be used to achieve reliable WCF services by forwarding WCF calls over messaging.

Running the sample

  1. Open the solution in Visual Studio.
  2. Press F5.
  3. Follow the instructions in the client's console window.

Verifying that the sample works correctly

  • When a message is sent which does not time out, Response 'Hello from handler' is displayed.
  • When a message is sent which does time out, Request failed due to: 'The request was cancelled after 00:00:05 because no response was received.' is displayed.

Code walk-through

The sample contains a self-hosted endpoint which uses the NServiceBus.Wcf and NServiceBus.Callbacks packages to achieve reliable WCF services over messaging.

The WCF package is configured to cancel requests after five seconds, and a named pipe binding is used to expose the service:

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

var wcf = endpointConfiguration.Wcf();
wcf.Binding(
    provider: _ => new BindingConfiguration(
        binding: new NetNamedPipeBinding(),
        address: new Uri("net.pipe://localhost/MyService")));
wcf.CancelAfter(
    provider: type => 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:

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

The proxy waits, asynchronously, until the response or 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