WPF与托管WCF服务之间的通信

时间:2019-01-17 07:36:04

标签: c# wpf wcf

我有一个启动WCF服务的控制台应用程序和一个小型WPF应用程序。每当试图出于测试目的而调用WCF服务上的方法时,我都试图在WPF应用程序中显示一个消息框。 我的代码基于this答案,但是syncContext为null。我该如何解决? 还是有其他/更好的方法来实现这一目标?

2 个答案:

答案 0 :(得分:0)

使用SignalR。很多信息herehereThis article看起来也很好。

对于实际代码,创建WCF服务并使用NuGet添加对SignalR的引用,然后添加中心类:

value

您还需要添加一个Owin启动类来启动SignalR集线器:

storeProducts(state, data){
             Object.assign(state.allProducts, data);
}

您的服务处理程序然后可以获取对该中心的引用,并将消息发送到与其连接的所有客户端:

public class ServiceMonitorHub : Hub
{
}

您的WPF客户端随后连接到此SignalR服务器并挂接处理程序以接收服务处理程序发送的消息,此示例包含一个调用该服务的按钮处理程序,以及与SignalR集线器的连接以接收消息反弹回来:

[assembly: OwinStartup(typeof(YourNamespace.SignalRStartup))]
namespace YourNamespace
{
    public class SignalRStartup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

}

请注意,客户端需要NuGet SignalR.Clients软件包(而不是仅SignalR)。

服务还有其他呼叫中心客户端的方法,this link显示了其他一些方法。

答案 1 :(得分:0)

也许您可以尝试使用ClientMessageInspector,客户端每次收到消息时都会调用该消息的AfterReceiveReply。

 public class MyClientMessageInspector : IClientMessageInspector
{
          Your message box
    public void AfterReceiveReply(ref Message reply, object correlationState)
    {
       show message in your message box
    }
    public MyClientMessageInspector ( ){

                       }

    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        return null;
    }
}

要注册Inspector,您需要使用endpointBehavior

  public class MyEndpointBehavior : IEndpointBehavior
{
    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {

    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.ClientMessageInspectors.Add( new MyClientMessageInspector();
    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {

    }

    public void Validate(ServiceEndpoint endpoint)
    {

    }
}

然后将行为添加到您的客户端。

 using (ChannelFactory<IService> ChannelFactory = new ChannelFactory<IService>("myservice"))
        {
            ChannelFactory.Endpoint.EndpointBehaviors.Add(new MyEndpointBehavior());
            IService service = ChannelFactory.CreateChannel();
          // call method


        }
相关问题