WCF的服务部能孤立地存在,需要寄宿于一个运行着的进程中,我们把承载WCF服务的进程成为宿主,为服务指定宿主的过程称为服务寄宿(Service Hosting)。
WCF服务的寄宿方式:自我寄宿(Self-Hosting)和IIS寄宿两种方式。
一、创建服务契约
- 服务契约定义一般采用接口的形式进行;
- 使用System.ServiceModel.ServiceContractAttribute特性应用在接口上,从而将其定义成服务契约;
- 接口函数上要显示的应用OperationContractAttribute特性,使其成为可访问的服务接口函数;
计算器小例子,如下:
1: [ServiceContract(Name="CalculatorService",Namespace="http://www.cnblogs.com/lisgang")]
2: public interface ICalculator
3: {
4: [OperationContract]
5: double Add(double x, double y);
6: [OperationContract]
7: double Subtract(double x, double y);
8: [OperationContract]
9: double Multiply(double x, double y);
10: [OperationContract]
11: double Divide(double x, double y);
12: }
- 服务实现服务契约的接口
1: public class CalculatorService : ICalculator
2: {
3: public double Add(double x, double y)
4: {
5: return x + y;
6: }
7: public double Subtract(double x, double y)
8: {
9: return x - y;
10: }
11: public double Multiply(double x, double y)
12: {
13: return x * y;
14: }
15: public double Divide(double x, double y)
16: {
17: return x / y;
18: }
1: static void Main(string[] args)
2: {
3: using (ServiceHost host=new ServiceHost(typeof(CalculatorService)))
4: {
5: host.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), "http://127.0.0.1:3721/calculatorservice");
6: if (host.Description.Behaviors.Find<ServiceMetadataBehavior>()==null)
7: {
8: ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
9: behavior.HttpGetEnabled = true;
10: behavior.HttpGetUrl = new Uri("http://127.0.0.1:3721/calculatorservice/metadata");
11: host.Description.Behaviors.Add(behavior);
12: }
13: host.Opened += delegate
14: {
15: Console.WriteLine("CalculatorService已经启动,按任意键终止服务!");
16: };
17: host.Open();
18: Console.Read();
19: }
20: }
1: class Program
2: {
3: static void Main(string[] args)
4: {
5: using (CalculatorServiceClient proxy=new CalculatorServiceClient())
6: {
7: Console.WriteLine(string.Format("x+y={2} when x={0} and y={1}",1,2,proxy.Add(1,2)));
8: Console.WriteLine(string.Format("x-y={2} when x={0} and y={1}", 1, 2, proxy.Subtract(1, 2)));
9: Console.WriteLine(string.Format("x*y={2} when x={0} and y={1}", 1, 2, proxy.Multiply(1, 2)));
10: Console.WriteLine(string.Format("x/y={2} when x={0} and y={1}", 1, 2, proxy.Divide(1, 2)));
11: }
12: Console.Read();
13: }
14: }
Steve 标记:
WCF学习笔记内容是学习大牛蒋金楠著作的WCF全面解析的内容,
自己做个总结与标记。