如何通过WCF与Windows服务进行通信?

时间:2016-06-04 19:54:21

标签: c# wcf windows-services

我有Windows服务,它在计时器刻度上运行任务。我还选择通过WCF命名管道通道与Windows服务进行通信。我可以创建WCF服务实例并打开它进行监听。但是我如何通过WCF访问依赖Windows服务的对象?

这就是我的Windows服务的样子:

.btn

所以我想要的是,当客户端进行查询时,可以访问WCF服务中的myObject。甚至可以在myObject上运行一个方法。

1 个答案:

答案 0 :(得分:1)

您可以使用静态属性在MyService(WCF托管实体)和MyCommunicationService(WCF服务实例)之间创建通信通道:

//This can be put into a separate DLL if needed.
public interface IMyHostCallbacks
{
    void HostCallback(string iSomeDataFromWCFToHost);
}

public static class Host
{
    public static IMyHostCallbacks Current;
}
public partial class MyService : ServiceBase, IMyHostCallbacks
{
    protected override void OnStart(string[] args)
    {
        //Set the static callback reference.
        Host.Current = this;

        if (m_svcHost != null) m_svcHost.Close();

        m_svcHost = new ServiceHost(typeof(MyCommunicationService));
        m_svcHost.Open();

        // initialize and work with myObject
    }

    //Here you have data from WCF and myObject available.
    void IMyHostCallbacks.HostCallback(string iSomeDataFromWCFToHost)
    {
        //Be careful here. 
        //Depending on your WCF service and WCF clients this might 
        //get called simultaneously from different threads.
        lock(myObject)
        {
            myObject.DoSomething(iSomeDataFromWCFToHost);
        }
    }
}

当然,您甚至可以将静态字段放入MyService类,但至少MyServiceMyCommunicationService之间的抽象不会受到影响。

现在,您可以在MyCommunicationService的任何地方:

void WCFServiceMethod()
{
    Host.Current.HostCallback("some data");
}