WCF原理性的东西,暂时还没有深入研究,只是在公司的项目中使用到了,会调用,然后再多做了一些了解,现在将它抽出来了一个小实例,写了一个WCF的demo。
我写的这个WCF.Demo主要包括数据契约和服务契约,UI客户端层和Host宿主层,基于http和net.tcp两种协议通信。
不多说,直接贴一张层次图片先,最后提供源码下载。
数据契约层(DataContracts)代码:
using System;using System.Collections.Generic;using System.Linq;using System.Runtime.Serialization;using System.Text;using System.Threading.Tasks;namespace WCF.DataContracts{ [DataContract()] public class CustomerData { [DataMember()] public string Name { set; get; } [DataMember()] public string Sex { set; get; } }}
服务契约接口层(WCF.ServiceContracts)
using System;using System.Collections.Generic;using System.Linq;using System.ServiceModel;using System.Text;using System.Threading.Tasks;namespace WCF.ServiceContracts{ [ServiceContract()] public interface ICustomerService { [OperationContract()] string ShowInfo(); }}
服务契约实现层(WCF.Services)
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using WCF.DataContracts;using WCF.ServiceContracts;namespace WCF.Services{ public class CustomerService : ICustomerService { public string ShowInfo() { CustomerData data = new CustomerData() { Name = "admin", Sex = "男" }; return "姓名是:" + data.Name + ",性别是:" + data.Sex; } }}
宿主层(两个文件)
Program
using System;using System.Collections.Generic;using System.Linq;using System.ServiceModel;using System.Text;using System.Threading.Tasks;using WCF.Services;namespace WCF.Hosting{ class Program { static void Main(string[] args) { ServiceHost hostForHello = new ServiceHost(typeof(CustomerService)); hostForHello.Open(); Console.WriteLine("WCF服务启动成功!"); Console.ReadLine(); } }}
app.config
客户端调用层(WCF.Client)
using System;using System.Collections.Generic;using System.Linq;using System.ServiceModel;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using WCF.ServiceContracts;namespace WCF.Client{ public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { using (ChannelFactorychannelFactory = new ChannelFactory ("helloEndPoint")) { ICustomerService helloService = channelFactory.CreateChannel(); using (helloService as IDisposable) { TextBox1.Text = helloService.ShowInfo(); } } } }}
客户端配置文件