WCF看似简单,实者掌握技巧,才能面向企业级架构开发设计。
1、首先建立一个空的解决方案,ch01,然后添加两个类库:Service——服务,Service.Interface——服务契约和两个控制台程序:Hosting——宿主程序,Client客户端程序。如图:
2、在每个项目都引用:System.ServiceModel.dll。
3、契约接口定义,创建ICalculator契约接口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
namespace Service.Interface
{
[ServiceContract(Name ="CalculatorService",Namespace ="http://www.artech.com/")]
public interface ICalculator
{
[OperationContract]
double Add(double x, double y);
[OperationContract]
double Subtract(double x, double y);
[OperationContract]
double Multiply(double x, double y);
[OperationContract]
double Divide(double x, double y);
}
}
4 创建服务类CalculatorService:
using Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Service
{
public class CalculatorService : ICalculator
{
public double Add(double x, double y)
{
return x + y;
}
public double Divide(double x, double y)
{
return x - y;
}
public double Multiply(double x, double y)
{
return x * y;
}
public double Subtract(double x, double y)
{
return x / y;
}
}
}
5、在控制台宿主程序修改代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hosting;
using Service;
using Service.Interface;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace Hosting
{
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(CalculatorService)))
{
host.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), “http://127.0.0.1:3721/CalculatorService“);
if (host.Description.Behaviors.Find ()== null)
{
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
behavior.HttpGetUrl = new Uri(“http://127.0.0.1:3721/CalculatorService/metadata“);
host.Description.Behaviors.Add(behavior);
}
host.Opened += delegate
{
Console.WriteLine("CalculatorService 已启动,按任意键盘终止服务!"); ;
};
host.Open();
Console.Read();
}
}
}
}
6.修改客户端程序(首先引用契约接口),代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using Service.Interface;
namespace Client
{
class Program
{
static void Main(string[] args)
{
using (ChannelFactory channelFactory = new ChannelFactory(new WSHttpBinding(), “http://127.0.0.1:3721/CalculatorService“))
{
ICalculator pxoxy = channelFactory.CreateChannel();
Console.WriteLine(“X+Y={2} where x={0} and y={1}”,1,2,pxoxy.Add(1,2));
Console.WriteLine(“X-Y={2} where x={0} and y={1}”, 1, 2, pxoxy.Subtract(1, 2));
Console.WriteLine(“X*Y={2} where x={0} and y={1}”, 1, 2, pxoxy.Multiply(1, 2));
Console.WriteLine(“X、Y={2} where x={0} and y={1}”, 1, 2, pxoxy.Divide(1, 2));
Console.Read();
}
}
}
}
7、设置启动项运行即可,如下图:
8、运行结果: