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
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.