I am using my WCF service to communicate with an external web-service which I do not control. Now, I would like to add a behavior to the operations being called such that, whenever it is impossible to communicate with the service, something should be logged to the database via a specifical stored procedure (no NLog/Log4Net in this case, it is really a stored procedure). However, I do not want to write code for this in each method calling the service, so I think a behavior should be more appropriate. How can I go about accomplis开发者_JS百科hing this?
You can use an IClientMessageInspector
in your client, which, whenever it receives a call after receiving the reply, it would check whether the response is successful or not (i.e., a fault). If it isn't, you can log it appropriately. The code below shows an example of a client message inspector doing this. And you can find out more about message inspectors at http://blogs.msdn.com/b/carlosfigueira/archive/2011/04/19/wcf-extensibility-message-inspectors.aspx.
public class StackOverflow_7484237
{
[ServiceContract]
public interface ITest
{
[OperationContract]
string Echo(string text);
}
public class Service : ITest
{
public string Echo(string text)
{
if (text == "throw")
{
throw new ArgumentException("This will cause a fault to be received at the client");
}
else
{
return text;
}
}
}
public class MyInspector : IEndpointBehavior, IClientMessageInspector
{
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(this);
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
}
public void Validate(ServiceEndpoint endpoint)
{
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
if (reply.IsFault)
{
Console.WriteLine("Log this fault: {0}", reply);
}
}
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
return null;
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "");
host.Open();
Console.WriteLine("Host opened");
var factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
factory.Endpoint.Behaviors.Add(new MyInspector());
var proxy = factory.CreateChannel();
Console.WriteLine(proxy.Echo("This won't throw"));
try
{
Console.WriteLine(proxy.Echo("throw"));
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e);
}
((IClientChannel)proxy).Close();
factory.Close();
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}
精彩评论