WCF服务怎样与宿主程序交互

来源:互联网 发布:胖熊数据库熊片截图 编辑:程序博客网 时间:2024/05/13 14:42

WCF服务必须host到一个宿主程序中才能够使用,但WCF服务如何与宿主程序进行交互呢?

如果宿主程序只是请求WCF服务的一个Operation很简单,只需要添加服务引用,像普通的客户端那样开发就可以了。

但如果希望当WCF服务被访问的时候主动与宿主程序进行交互,则如何处理呢?这里用个例子来说明:WCF服务WAFService继承自IWAFService,其只有一个Operation:void DisplayContent(string content),该服务host在一个WinForm程序中,当客户端访问DisplayContent时,参数content的内容将在WinForm的List控件LBContent中被显示。

这里有两个重点:

一是需要对WCF服务进行较多的控制,因此需要用构造函数ServiceHost(Object, Uri()),而不是通常的ServiceHost(Type, Uri()),前者直接把WCF服务实例传递给ServiceHost对象,因此WCF服务的实例管理必须是Single即InstanceContextMode = InstanceContextMode.Single,而后者传递的只是WCF服务的类型,由ServiceHost来决定如何在适当的时候创建和销毁WCF服务实例;

二是在WCF服务的类定义中,需要添加一个公开的delegate,当WCF服务的Operation被调用时用来回调宿主程序中的方法。

该实例程序的主要代码如下所示:

namespace WFAWCF{    public delegate void DisplayContent(string content);        [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]    public class WAFService : IWAFService    {        public DisplayContent AddContent = null;        public void DealWithContent(string content)        {            if (!string.IsNullOrEmpty(content))            {                if(null != AddContent)                    AddContent(content);                Console.WriteLine(content);            }        }    }}
WCF服务程序



namespace WFAWCF{    public partial class Form1 : Form    {        private ServiceHost host = null;        public Form1()        {            InitializeComponent();        }        private void Form1_Load(object sender, EventArgs e)        {            LBContent.Items.Clear();            WAFService service = new WAFService();            service.AddContent += this.AddContent;            host = new ServiceHost(service);            host.Open();        }        private void Form1_FormClosing(object sender, FormClosingEventArgs e)        {            if(null != host)            {                host.Close();            }        }        public void AddContent(string content)        {            LBContent.Items.Add(content);        }    }}

宿主程序


对于不太重要的接口定义和配置程序,在此略去。

原创粉丝点击