IServiceBehavior, IDispatchMessageInspector and Endpoints

You can inject an IDispatchMessageInspector implementation in Windows Communication Foundation on the server side either through an IEndpointBehavior or through an IServiceBehavior. Doing it through an endpoint behavior is quite obvious how to do it, but I didn't see much documentation (at least up to date one) on how you could do so using a service behavior instead.

The answer seems to be to do so by looking for each of the EndpointDispatcher instances associated with the ServiceHost you get as an argument in your ApplyDispatchBehavior(); through them you get access to the corresponding DispatchRuntime for that endpoint. Here's some sample code:

The IsInstrumentableEndpoint() call is somewhat interesting. In a service behavior you get access to all endpoints associated with a single service, unlike an endpoint behavior which is obviously endpoint-specific. However, this does not mean you necessarily want to apply your behavior to all endpoints exposed by the service. For example, in my case, I was only interested in the "user" endpoints, and not in the WSDL or Metadata Exchange (MEX) endpoints; both of which you'd normally see in your service behavior if they are enabled.

Right now, I'm implementing my IsInstrumentableEndpoint() method by simply checking if it's not the MEX or WSDL endpoint by looking at the ContractNamespace associated with the endpoint ( "http://schemas.microsoft.com/2006/04/mex" for MEX and "http://schemas.microsoft.com/2006/04/http/metadata" for the ?wsdl endpoint). Probably not the most elegant way, but it does the trick.