[英]How to fire an event (client side) when I call a WCF service
我想在每次调用WCF服务时触发一个事件。
我尝试了以下方法:
var factory = new ChannelFactory<TService>(binding, endPointAdress);
factory.Credentials.UserName.UserName = username;
factory.Credentials.UserName.Password = password;
var proxy = factory.CreateChannel();
((IContextChannel)this.Proxy).Opened += new EventHandler(FactoryOpeningEventHandler);
this.Factory.Opened += new EventHandler(FactoryOpeningEventHandler);
上面的问题是,仅在打开代理时才调用该事件,但是我想在通过该代理进行调用时(不仅是在打开时)触发该事件。 我知道没有针对IContextChannel的事件可以执行我想要的操作,因此我想采用一种解决方法。
首先,创建一个检查器类,该类同时实现IDispatchMessageInspector
(发送时)和IClientMessageInspector
(接收时)接口。
public class SendReceiveInspector : IDispatchMessageInspector, IClientMessageInspector
{
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
// TODO: Fire your event here if needed
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
// TODO: Fire your event here if needed
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
// TODO: Fire your event here if needed
}
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
// TODO: Fire your event here if needed
return null;
}
}
拥有检查员课程后,您必须通过行为进行注册。
public class SendReceiveBehavior : IEndpointBehavior, IServiceBehavior
{
void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(new SendReceiveInspector());
}
void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new SendReceiveInspector());
}
void IEndpointBehavior.AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
// Leave empty
}
void IEndpointBehavior.Validate(ServiceEndpoint endpoint)
{
// Leave empty
}
void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription desc, ServiceHostBase host)
{
foreach (ChannelDispatcher cDispatcher in host.ChannelDispatchers)
{
foreach (EndpointDispatcher eDispatcher in cDispatcher.Endpoints)
{
eDispatcher.DispatchRuntime.MessageInspectors.Add(new SendReceiveInspector());
}
}
}
void IServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
// Leave empty
}
void IServiceBehavior.Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
// Leave empty
}
}
最后,您必须将该行为注册到服务描述中:
host.Description.Behaviors.Add(new SendReceiveBehavior ());
foreach (ServiceEndpoint se in host.Description.Endpoints)
se.Behaviors.Add(new SendReceiveBehavior ());
您可以在http://msdn.microsoft.com/zh-cn/magazine/cc163302.aspx上了解有关扩展WCF的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.