每次调用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没有可以做我想做的事情,所以我希望有一个解决方法。
答案 0 :(得分:6)
首先创建一个同时实现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 ());
了解有关扩展WCF的详情