这个博客真的难。第一种方法前面已经介绍了,直接第二种方法:
二、创建代理,引用服务接口所在的类库和服务实现类的类库
static void Main(string[] args)
{
//基于地址和绑定对象创建一个ChannelFactory<ICalculator> 通过代码
using (ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>(new WSHttpBinding(), "http://127.0.0.1:3721/calculatorService"))
{
//创建服务代理对象
ICalculator proxy = channelFactory.CreateChannel();
//调用计算器方法
Console.WriteLine("x+y={2} when x={0} and y={1}", 1, 2, proxy.Add(1, 2));
Console.WriteLine("x-y={2} when x={0} and y={1}", 1, 2, proxy.Subtract(1, 2));
Console.WriteLine("x*y={2} when x={0} and y={1}", 1, 2, proxy.Multiply(1, 2));
Console.WriteLine("x/y={2} when x={0} and y={1}", 1, 2, proxy.Divide(1, 2));
Console.ReadLine();
}
}
三、服务代理的内容通过配置实现(个人偏向这种方法):
static void Main(string[] args)
{
using (ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>("calculatorService"))
{
//创建服务代理对象
ICalculator proxy = channelFactory.CreateChannel();
//调用计算器方法
Console.WriteLine("x+y={2} when x={0} and y={1}", 1, 2, proxy.Add(1, 2));
Console.WriteLine("x-y={2} when x={0} and y={1}", 1, 2, proxy.Subtract(1, 2));
Console.WriteLine("x*y={2} when x={0} and y={1}", 1, 2, proxy.Multiply(1, 2));
Console.WriteLine("x/y={2} when x={0} and y={1}", 1, 2, proxy.Divide(1, 2));
Console.ReadLine();
}
}
客户端的配置文件,自己创建一个配置文件,app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<client>
<endpoint name="calculatorService" address="http://127.0.0.1:3721/CalculatorService" binding="wsHttpBinding" contract="Service.Interface.ICalculator"/>
</client>
</system.serviceModel>
</configuration>
其实总的来说,是两种,一种是添加服务引用,另一种是引用类库,然后使用代理。第三种方法只是用配置去实现客户端的方法罢了。仔细看添加引用服务的时候,其实他也生成了一个配置文件,哈哈。如下图:跟自己创建的区别不是特别的大:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_CalculatorService" />
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://127.0.0.1:3721/calculatorservice" binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_CalculatorService" contract="Service.CalculatorService"
name="WSHttpBinding_CalculatorService">
<identity>
<userPrincipalName value="DESKTOP-F4TGBAT\Administrator" />
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>