wcf中创建宿主程序
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using System.ServiceModel.Channels; namespace wcfservicehost { class Program { static void Main(string[] args) { using (MyhelloHost Host = new MyhelloHost()) { Host.Open(); Console.Read(); } } } public class MyhelloHost : IDisposable { /// <summary> /// 定义一个服务对象 /// </summary> private ServiceHost _myhost; public ServiceHost Myhost { get { return _myhost; } } /// <summary> /// 定义一个基地址 /// </summary> public const string BaseAddress = "net.pipe://localhost"; /// <summary> /// 可选地址 /// </summary> public const string HelleServiceAddress = "Hello"; /// <summary> ///服务契约类型 /// </summary> public static readonly Type ServiceType = typeof(wcfservice.HelloService); /// <summary> /// 服务契约接口 /// </summary> public static readonly Type ContraceType = typeof(wcfservice.IHelloService); /// <summary> /// 服务定义一个绑定 /// </summary> public static readonly Binding HelloBing = new NetNamedPipeBinding(); /// <summary> /// 构造服务对象 /// </summary> protected void CreateHelloServiceHost() { //创建服务对象 _myhost = new ServiceHost(ServiceType, new Uri[] { new Uri(BaseAddress) }); //添加服务终结点 _myhost.AddServiceEndpoint(ContraceType, HelloBing, HelleServiceAddress); } /// <summary> /// 打开服务 /// </summary> public void Open() { Console.WriteLine("开始启动服务....."); Myhost.Open(); Console.WriteLine("服务已经启动....."); } /// <summary> /// 构造函数 /// </summary> public MyhelloHost() { CreateHelloServiceHost(); } /// <summary> /// 销毁服务宿主对象实例 /// </summary> public void Dispose() { if (_myhost != null) { (_myhost as IDisposable).Dispose(); } } } }
客户端程序
using System; using System.Collections.Generic; using System.Linq; using System.Text; using wcfservice; using System.ServiceModel; using System.ServiceModel.Channels; namespace wcfclient { class Program { static void Main(string[] args) { using (HelloProxy proxy = new HelloProxy()) { //利用代理调用服务 Console.WriteLine(proxy.say("张三")); Console.Read(); } } } //硬编码定义服务契约 [ServiceContract] interface Iservice { //服务操作 [OperationContract] string say(string name); } /// <summary> /// 客户端代理类型 /// </summary> class HelloProxy : ClientBase<IHelloService>, Iservice { //硬编码定义绑定 public static readonly Binding HelloBind = new NetNamedPipeBinding(); //硬编码定义地址 public static readonly EndpointAddress HelloAddress = new EndpointAddress(new Uri("net.pipe://localhost/Hello")); /// <summary> /// 构造方法 /// </summary> public HelloProxy() : base(HelloBind, HelloAddress) { } public string say(string name) { //使用Channel属性对服务进行调用 return Channel.Sayhell(name); } } }