使用WCF通过Windows服务和Windows窗体应用程序进行通信

时间:2018-06-12 13:12:45

标签: c# winforms wcf windows-services

目前,我在Visual Studio 2017中有两个解决方案:

  1. Windows表单应用程序
  2. 托管WCF服务类库(.dll)的Windows服务应用程序
  3. 我需要以循环方式在它们之间进行通信,如下图所示。数字代表订单。

    enter image description here

    问题是,我实际上能够通过使用请求 - 重放操作合同(由数字1和4表示)在WF和WCF应用程序之间进行通信。但我不知道如何执行第2步和第3步。

    WCF界面代码:

    namespace SmithWcfService {
        [ServiceContract]
        public interface ISmithWcfService {
            [OperationContract]
            void SendRequest( ); //Operation called by Windows Forms
        }
    }
    

    WCF接口实施代码

    namespace SmithWcfService {
        public class SmithWcfService : ISmithWcfService {
            public void SendRequest( ) {
                //Ok, now I need to call Windows service application
            }
        }
    }
    

    Windows服务代码

    namespace SmithWindowsService {
        static class Program {
            static void Main( ) {
                ServiceBase[ ] ServicesToRun;
                ServicesToRun = new ServiceBase[ ] {
                    new SmithWindowsService( )
                };
                ServiceBase.Run( ServicesToRun );
            }
        }
    }
    
    namespace SmithWindowsService {    
        public partial class SmithWindowsService : ServiceBase {
            private ServiceHost host;
    
            public SmithWindowsService( ) {
                InitializeComponent( );
            }
    
            protected override void OnStart( string[ ] args ) {
                host = new ServiceHost( typeof( SmithWcfService.SmithWcfService ) );
                host.Open( );
            }
        }
    }
    

1 个答案:

答案 0 :(得分:1)

如果Windows服务托管您的WCF服务,您可以在服务启动时简单地传递它需要的任何内容(回调,值,设置)。您可以将Windows服务的方法传递为WCF服务应调用的Func<Input2, Output3>

如果没有您的代码,您很难告诉 你需要把它放在哪里。通常情况下,它会进入您的自定义ServiceHostFactory

回调服务示例:

namespace SmithWcfService 
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] 
    public class SmithWcfService : ISmithWcfService 
    {
        private Func<string, int> callback;

        public SmithWcfService(Func<string, int> callback)
        {
            this.callback = callback;
        }

        public void SendRequest() 
        {
            //Ok, now I need to call Windows service application:
            var output = this.callback("input");
        }
    }
}

托管示例:

namespace SmithWindowsService 
{    
    public partial class SmithWindowsService : ServiceBase 
    {
        private ServiceHost host;

        public SmithWindowsService( ) 
        {
            InitializeComponent( );
        }

        protected override void OnStart(string[] args) 
        {
            var instance = new SmithWcfService.SmithWcfService(this.SomeMethodYouWantToCallIn);
            host = new ServiceHost(instance, new Uri("your.url.com"));
            host.Open( );
        } 

        private int SomeMethodYouWantToCall(string data)
        {
            // do things...
        }
    }
}