最近学了下WCF,作为微软推出的分布式系统解决方案,确实优秀。
做为初学者,这里只能记录学到的内容,为自己的学习做下参考。
1.首先程序需要定义Contract(契约)
在wcf上contract的功能就是要定义一个service包含哪些operation.以及每个Operation的签名方法。而从消息交换的角度来说,contract定义了调用service采取的消息交换模式。因为调用service的过程实际是消息交互的过程。(所以WCF的调用实际非oo模式),调用模式Oneway, Request/Response,和Duplex。其中Request/Response为默认。
让一个类或者接口成为Contract非常简单。引用using System.Servicemodel; 然后声明【ServiceContract】即可。如下例中interface ICalculator就是Contract了。
在这个接口内函数声明【OperationContract】那么这个函数变成为了Service的一个可访问性
namespace WCFService.Contract { [ServiceContract] public interface ICalculator { [OperationContract] double Add(double x, double y); } }
|
2.定义Service
Contract实际是一个契约,或者是一种约定,Service是实现这个Contract,这个比较简单,直接看代码
namespace WCFService.Service { public class CalculatorService:ICalculator { #region IGeneralCalculator Members
public double Add(double x, double y) { return x + y; }
#endregion } }
|
3.host 打开服务
WCF中Service和Client的交互式通过endpoint进行的。endpoint包括3部分:Address;Binding;Contract . Host的本质就是把service放置到运行的进程中,并且以endpoint的方式暴露出来,以对client进行监听
namespace WCFService.Hosting { class Program {
static void Main(string[] args)
{
HostingServiceViaCode();
}
static void HostingServiceViaCode() {
Uri baseUri = new Uri("http://localhost:8080/calculatorService"); //这里实际是endpoint的Address using (ServiceHost calculatorServiceHost = new ServiceHost(typeof(CalculatorService), baseUri))//建立一个host,这个host暴露了CalculatorService,地址为baseUri { BasicHttpBinding Binding = new BasicHttpBinding(); //这里就是endpoint的binding..the empty string indicates the Address equals base Addressthe empty string indicates the Address equals base Address
calculatorServiceHost.AddServiceEndpoint(typeof(ICalculator), Binding, string.Empty); ServiceMetadataBehavior behavior = calculatorServiceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
//If the Service metadata behavior has not to added to the Service. we will create a new one and evaluate the HttpGetEnabled&HttpGetUrl to make outer world can retrieve to metadata.
if (behavior == null)
{
behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
//HttpGetUrl is absolute or relative based on base Address
behavior.HttpGetUrl = baseUri;
//We must add the new behavior created to the behavior collection, otherwize it will never take effect.
calculatorServiceHost.Description.Behaviors.Add(behavior);
}
//if the metadata behavior exists in the behavior collection, we just need to evaluate the HttpGetEnabled&HttpGetUrl
else
{
behavior.HttpGetEnabled = true;
behavior.HttpGetUrl = baseUri;
}
//Add the opened event handler to make a friendly message displayed after opening the Service host indicating the Service begin to listen to request from Clients.
calculatorServiceHost.Opened += delegate { Console.WriteLine("Calculator Service begin to listen via the Address:{0}", calculatorServiceHost.BaseAddresses[0].ToString()); };
//Open the Service host make it begin to listen to the Clients.
calculatorServiceHost.Open();
Console.Read();
}
}
|
没有完成了。有要事要办。空了补好
阅读(738) | 评论(0) | 转发(0) |