John K
John K

Reputation: 830

WCF 4.0 RouterService message Inspector

I am using the new .Net 4.0 RouterService and have a requirement for the router to log the messages going back and forth. I need to do this by accessing the actual message being routed.

How do I implement a MessageInspector on the Router programatically? Or is there some alternative to using a MessageInspector?

Upvotes: 2

Views: 1115

Answers (1)

John K
John K

Reputation: 830

Found the answer:

internal class MessageLogger : IClientMessageInspector, IDispatchMessageInspector, IEndpointBehavior {
    private readonly ILoggingProvider _Logging;

    public MessageLogger(ILoggingProvider logging) {
        _Logging = logging;
    }

    #region IDispatchMessageInspector Members

    public object BeforeSendRequest(ref Message request, IClientChannel channel) {
        _Logging.LogMessage("Routing message to service");
        return null;
    }

    public void AfterReceiveReply(ref Message reply, object correlationState) {
        _Logging.LogMessage("Response from service received");
    }

    #endregion


    #region IDispatchMessageInspector Members

    public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) {
        _Logging.LogMessage("Message received from client");

        return null;
    }

    public void BeforeSendReply(ref Message reply, object correlationState) {
        _Logging.LogMessage("Sending response to client");
    }

    #endregion

    #region IEndpointBehavior Members

    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) {
        return;
    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) {
        clientRuntime.MessageInspectors.Add(this);
    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) {
        endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this);
    }

    public void Validate(ServiceEndpoint endpoint) { return; }

    #endregion
}

Then hookup to the router endpoint like so:

public class RouterServiceHost : ServiceHost {
    ...
    public RouterServiceHost() {
        ...
        var endpoint = this.AddServiceEndpoint(routerContract, routerBinding, routerAddress);
        endpoint.Behaviors.Add(new MessageLogger(_Logging));
    }
}

Upvotes: 1

Related Questions