我正在使用新的.Net 4.0 RouterService,并要求路由器记录来回传递的消息。我需要通过访问路由的实际消息来完成此操作。
如何以编程方式在路由器上实现MessageInspector?或者是否有使用MessageInspector的替代方法?
答案 0 :(得分:1)
找到答案:
internal class MessageLogger : IClientMessageInspector, IDispatchMessageInspector, IEndpointBehavior {
private readonly ILoggingProvider _Logging;
public MessageLogger(ILoggingProvider logging) {
_Logging = logging;
}
#region IDispatchMessageInspector Members
public object BeforeSendRequest(ref Message request, IClientChannel channel) {
_Logging.LogMessage("Routing message to service");
return null;
}
public void AfterReceiveReply(ref Message reply, object correlationState) {
_Logging.LogMessage("Response from service received");
}
#endregion
#region IDispatchMessageInspector Members
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) {
_Logging.LogMessage("Message received from client");
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState) {
_Logging.LogMessage("Sending response to client");
}
#endregion
#region IEndpointBehavior Members
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) {
return;
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) {
clientRuntime.MessageInspectors.Add(this);
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) {
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this);
}
public void Validate(ServiceEndpoint endpoint) { return; }
#endregion
}
然后连接到路由器端点,如下所示:
public class RouterServiceHost : ServiceHost {
...
public RouterServiceHost() {
...
var endpoint = this.AddServiceEndpoint(routerContract, routerBinding, routerAddress);
endpoint.Behaviors.Add(new MessageLogger(_Logging));
}
}