您的位置:首页 > 其它

学习WCF之路5:ClientBase的使用

2016-06-08 08:41 218 查看
       在上篇中,我们利用通道工厂ChannelFactory<>类创建了通道,实现了和服务端的通信。今天使用ClientBase<>类来实现同样的功能。

      ClientBase<>类也是一个泛型类,接受服务协定作为泛型参数,与ChannelFactory<>不同的是,这个类是一个基类,即抽象类,是不能实例化成对象直接使用的,我们需要自己写一个类来继承这个类,我们新写的类实例化出来就是客户端代理了,这个对象可以调用基类的一些受保护的方法来实现通信。

实现步骤:

(1)新建一个控制台应用程序作为客户端,并且添加System.ServiceModel引用。

(2)编写服务协定,内容和之前一致。

[ServiceContract]
public interface IHelloWCF
{
[OperationContract]
string PHelloWCF();
}

(3)编写客户端代理类,并且实现接口。
public class HelloWCFClient : ClientBase<IHelloWCF>, IHelloWCF
{
public HelloWCFClient(System.ServiceModel.Channels.Binding binding, EndpointAddress remoteAdrress) : base(binding, remoteAdrress)
{

}

public string PHelloWCF()
{
return base.Channel.PHelloWCF();
}
}上文提到,使用ClientBase<>类需要新建一个类来继承,该类就是客户端代理类。(注意:继承要写在前面,实现接口要写在后面)
ClientBase<>有许多的构造函数,接受不同种类的参数来创建代理类对象,其实这些参数都是元数据信息,刚才我们已经通过泛型参数传递给基类服务协定这个元数据了,现在基类还需要绑定和终结点地址这两个元数据才能正确创建连接,所以我们继承的新类应该把这个构造函数给重载一下接受这两种元数据参数并传递给基类。

定义了接口,就要实现,但是这里是客户端,所以是通过通信让服务端做。代理类虽然实现了服务协定的方法,但是在方法中,他调用了基类(就是ClientBase<>)上的通道,并通过通道调用了了协定方法。

(4)编写程序主体。 WSHttpBinding binding = new WSHttpBinding();
EndpointAddress remoteAddress = new EndpointAddress("http://localhost/IISService/HelloWCF.svc");
HelloWCFClient client = new HelloWCFClient(binding,remotAddress);

string result = client.PHelloWCF();

client.Close();

Console.WriteLine(result);
Console.ReadLine();该内容与前几篇内容一致,就不再赘述。
(5)保存,运行,OK,结果一致。

引申:也可以通过配置文件来进行配置终结点地址与绑定,避免硬编码。

添加app.config配置文件,内容:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<system.serviceModel>
<client>
<endpoint binding="wsHttpBinding" address="http://localhost/IISService/HelloWCF.svc" contract="ClientBase.IHelloWCF"/>
</client>
</system.serviceModel>
</configuration>注意看后面的contract,他的完全限定名的命名空间是客户端程序的命名空间ConsoleClient,这也表示这个类型是定义在本地的,不要搞错了。

配置写完,程序就得改,内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.ServiceModel;

namespace ConsoleClient
{
class Program
{
static void Main(string[] args)
{
HelloWCFClient client = new HelloWCFClient();

string result = client.HelloWCF();

client.Close();

Console.WriteLine(result);
Console.ReadLine();
}
}

[ServiceContract]
public interface IHelloWCF
{
[OperationContract]
string HelloWCF();
}

public class HelloWCFClient : ClientBase<IHelloWCF>, IHelloWCF
{
public HelloWCFClient()
: base()
{

}

public HelloWCFClient(System.ServiceModel.Channels.Binding binding, EndpointAddress remoteAddress)
: base(binding, remoteAddress)
{

}

public string HelloWCF()
{
return base.Channel.PHelloWCF();
}
}
}


保存运行,结果应该一致。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: