Adding WCF Message Inspectors at Run Time

I created a custom ServiceHost that I would like to use to automatically add a message inspector to each service endpoint that runs on it. I created a MessageInspector that implements IDispatchMessageInspector and IClientMessageInspector and found the following code that should add it to each endpoint:

foreach (ChannelDispatcher channel in this.ChannelDispatchers) {
  foreach (EndpointDispatcher endpoint in channel.Endpoints) {
      endpoint.DispatchRuntime.MessageInspectors.Add(new MyMessageInspector());
   }
}

The problem I am facing is that the ChannelDispatchers collection is empty until servicehost is open, which means that I cannot run this code in the constructor. I created an event handler for the Opened event and used this code instead, but then I get the following error when trying to add an endpoint:

This value cannot be changed after a ServiceHost has been opened

It seems like I got into some kind of Catch 22, is this the function I'm looking for in WCF?

Thank,

Mike

+3
source share
1 answer

To add a message inspector to a service endpoint, this must be accomplished by implementing either IServiceBehavior or IEndpointBehavior. In the case of the ServiceBehavior that I ended up using, I put the code above in the ApplyDispatch () method for IServiceBehavior. Then I added the behavior to my ServiceHost imperatively, although I could do this through configuration by creating a BehaviorExtensionElement.

+3
source

Source: https://habr.com/ru/post/1782464/


All Articles