WCF笔记是在看《精通c#5.0与.NET4.5高级编程》和《C#高级编程(第8版)》两本书时,记录和总结相关知识点以及个人理解。
WCF本质上说是一套软件开发包。提供丰富的功能,包括托管、服务实例管理、异步、安全、事务管理、离线队列等。
WCF体系基本包括4个方面:
(1)契约:属于一个服务公开接口的一部分。告诉SOA系统其他节点此服务是“干什么的”。
(2)服务运行行为:服务运行方面定义了服务在运行时的具体行为。如果说契约描述了服务是“干什么”的,那服务运行就在一定程度上描述了服务是“怎么干的”
(3)消息:包含了消息的传输方式、消息的编码与解码。消息方面的内容基本属于服务边界以内的具体实现。
(4)激活和寄宿:激活和宿主属于WCF 程序的部署方式。
WCF基本概念介绍
1、地址:。一个服务的地址由一个URI来表示。如下:
http://localhost:8080/servce net.tcp://dc2web1:9023/MySevice
net.mamq://localhost/MyMsMqService
2、绑定:绑定定义了服务与外部通信的方式。它由一组称为绑定元素的元素构造而成,这些元素组合在一起以形成通信基础结构。包含:通信所使用的协议、消息编码方式、消息安全保障策略、通信堆栈的其他任何要素。
3、契约:包含服务契约、数据契约、错误契约和消息契约。
4、终结点:终结点由3 个要素组成,分别是地址、绑定和契约。
5、元数据:服务的元数据描述服务的特征。
6、宿主:服务必须承载于某个进程中。宿主是控制服务的生存期的应用程序。
第一个WCF程序之HelloWorld
(1)helloworld 服务契约定义
IService:
[ServiceContract] public interface IService1 { // TODO: 在此添加您的服务操作 [OperationContract] String HelloWorld(String name); //放入服务 }
Service
public class Service1 : IService1 { public String HelloWorld(String name) { return name + "say=>HelloWorld!"; } }
(2) 宿主程序(服务端)
public class MySerivceHost : IDisposable { private ServiceHost _myHost; //public const String BaseAddress = "net.pipe://127.0.0.1";
//public const String BaseAddress = "net.pipe://localhost"
public const String HelloWorldServiceAddress = "FristWCFService"; public static readonly Type ContractType = typeof(FristWCFService.IService1); public static readonly Type ServiceType = typeof(FristWCFService.Service1); public static readonly Binding HelloWorldBinding = new NetNamedPipeBinding(); protected void ConstructServiceHost() { _myHost = new ServiceHost(ServiceType, new Uri[] { new Uri(BaseAddress) }); _myHost.AddServiceEndpoint(ContractType, HelloWorldBinding, HelloWorldServiceAddress); } public ServiceHost Host { get { return _myHost; } } public void Open() { Console.WriteLine("正在开启服务..."); _myHost.Open(); Console.WriteLine("服务已启动..."); } public MySerivceHost() { ConstructServiceHost(); } public void Dispose() { if (_myHost != null) (_myHost as IDisposable).Dispose(); } }
在main函数中:
using (MySerivceHost host = new MySerivceHost()) { host.Open(); Console.Read(); }
此处BaseAddress定义net.pipe通信。
(3) 客户端程序:
[ServiceContract] interface IService1 { [OperationContract] String HelloWorld(String name); } class HelloWorldProxy : ClientBase<IService1>,IService1 { public static readonly Binding HelloWorldBinding = new NetNamedPipeBinding(); public static readonly EndpointAddress HelloWorldAddress = new EndpointAddress(new Uri("net.pipe://localhost/FristWCFService")); public HelloWorldProxy():base(HelloWorldBinding,HelloWorldAddress) { } public String HelloWorld(String name) { return Channel.HelloWorld(name); } }
运行结果: