Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding WCF Message Inspectors at Runtime

I have created a custom ServiceHost that I would like to use to automatically add a message inspector to every endpoint of a service that is running on it. I have created a MessageInspector that implements IDispatchMessageInspector and IClientMessageInspector and have found the following code that is supposed to add it to every endpoint:

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

The problem I run into is that the ChannelDispatchers collection is empty until the servicehost is opened, which means I can't run this code in the constructor. I created an event handler for the Opened event and used that code in there 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 that I am caught in some sort of a Catch 22, is the functionality I am seeking possible within WCF?

Thanks,

Mike

like image 401
mclark1129 Avatar asked Feb 16 '26 13:02

mclark1129


1 Answers

In order to add a message inspector to a service endpoint, this has to be done by implementing either a IServiceBehavior, or an IEndpointBehavior. In the case of a ServiceBehavior, which I ended up using, I placed the code above into the ApplyDispatch() method of the IServiceBehavior. I then added the behavior to my ServiceHost imperatively, although I could have done it through configuration by creating a BehaviorExtensionElement.

like image 92
mclark1129 Avatar answered Feb 18 '26 06:02

mclark1129



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!