Here are the relevant code snipets for anyone else attemping this
First an instance of the IDispatchMessageInspector
public class CustomResponseFormatterMessageInspector : IDispatchMessageInspector
{
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
var prop = (HttpResponseMessageProperty)reply.Properties[HttpResponseMessageProperty.Name];
if (prop.StatusCode == HttpStatusCode.NotFound)
{
ErrorResponse(ref reply);
}
}
private void ErrorResponse(ref Message original)
{
const string ERROR_HTML = @"<html><HEAD><TITLE>Request Error</TITLE></HEAD><BODY> <H1>My Error processing request {1}</H1><P>{0}</P></BODY></html>";
XElement response = XElement.Load(new StringReader(string.Format(ERROR_HTML, "A Resource does not exsist at this location.", HttpStatusCode.NotFound)));
Message reply = Message.CreateMessage(original.Version, null, response);
reply.Headers.CopyHeadersFrom(original);
reply.Properties.CopyProperties(original.Properties);
original = reply;
}
}
Then to inject this into the IServiceBehaviour
I added
ed.DispatchRuntime.MessageInspectors.Add(new CustomResponseFormatterMessageInspector());
There may be other code in this that is relevant to my implementation but that is all i added.
public class DependencyInjectionServiceBehavior : IServiceBehavior
{
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers)
{
var cd = cdb as ChannelDispatcher;
if (cd != null)
{
foreach (EndpointDispatcher ed in cd.Endpoints)
{
ed.DispatchRuntime.InstanceProvider =
new DependencyInjectionInstanceProvider(serviceDescription.ServiceType);
ed.DispatchRuntime.MessageInspectors.Add(new CustomResponseFormatterMessageInspector());
}
}
}
}
public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
}
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
}