WPF应用程序中的net.pipe服务主机

时间:2014-03-04 05:14:09

标签: wpf wcf net.pipe

合同:

[ServiceContract]
public interface IDaemonService {
    [OperationContract]
    void SendNotification(DaemonNotification notification);
}

服务:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class DaemonService : IDaemonService {
    public DaemonService() {
    }

    public void SendNotification(DaemonNotification notification) {
        App.NotificationWindow.Notify(notification);
    }
}

在WPF应用程序中,我执行以下操作:

using (host = new ServiceHost(typeof (DaemonService), new[] {new Uri("net.pipe://localhost")})) {
            host.AddServiceEndpoint(typeof (IDaemonService), new NetNamedPipeBinding(), "AkmDaemon");                
            host.Open();
        } 

这个WPF应用程序会启动另一个这样的应用程序:

Task.Factory.StartNew(() => {
                var tpm = new Process { StartInfo = { FileName = "TPM" } };
                tpm.Start();
                }
            });

名为TPM的应用程序正常启动。然后我在Visual Studio的调试菜单中附加进程,我看到客户端说没有人在端点上监听。

这是客户:

 [Export(typeof(DaemonClient))]
public class DaemonClient : IHandle<DaemonNotification> {
    private readonly ChannelFactory<IDaemonService> channelFactory;
    private readonly IDaemonService daemonServiceChannel;

    public DaemonClient(IEventAggregator eventAggregator) {           
        EventAggregator = eventAggregator;
        EventAggregator.Subscribe(this);

        channelFactory = new ChannelFactory<IDaemonService>(new NetNamedPipeBinding(),
            new EndpointAddress("net.pipe://localhost/AkmDaemon"));            
        daemonServiceChannel = channelFactory.CreateChannel();
    }

    public IEventAggregator EventAggregator { get; private set; }

    public void Handle(DaemonNotification message) {
        daemonServiceChannel.SendNotification(message); //Here I see that the endpoint //is not found
    }

    public void Close() {
        channelFactory.Close();
    }
}

EndpointNotFoundException没有端点监听“net.pipe:// localhost / AkmDaemon”... blablabla

1 个答案:

答案 0 :(得分:2)

您正在using语句中创建ServiceHost,因此它会在Open调用之后立即处理。 Dispose调用将关闭ServiceHost。

using (host = new ServiceHost(...))
{
    host.AddServiceEndpoint(...);
    host.Open();
}
// ServiceHost.Dispose() called here

只需删除使用块。