学习光看书看视频还是不行,按照第一节的Demo,自己写一下,加深印象。
第一节的笔记纪录:
【学习】构建WCF面向服务的应用程序系列课程笔记:(1) WCF概要
这是一个最简单的WCF程序,在这个例子中,只使用了类库与控制台应用程序,没有使用VS中自带创建WCF Service这些相关内容,有助于理解WCF的建立服务,Host与调用。
首先创建Service,类库HelloInDigo,创建类HelloInDigoService,在类中定义契约IHelloInDigoService,并实现它。
namespace HelloDigo
{
[ServiceContract]
public interface IHelloInDigoService
{
[OperationContract]
string Hello(string message);
}
public class HelloInDigoService : IHelloInDigoService
{
public string Hello(string message)
{
return string.Format("服务调用于{0},返回消息为{1}",DateTime.Now, message);
}
}
}
需要引用System.ServiceModel DLL
创建类库Host,使客户端可以通过Host调用Service
namespace Host
{
class Program
{
static void Main(string[] args)
{
//实例ServiceHost时,里面的类型应该是类,而不是契约接口
using (ServiceHost host = new ServiceHost(typeof(HelloDigo.HelloInDigoService)))
{
host.AddServiceEndpoint(typeof(HelloDigo.IHelloInDigoService), new NetTcpBinding(), "net.tcp://localhost:9000/HelloInDigo");
host.Open();
Console.ReadLine();
}
}
}
}
需要引用Service类库HelloInDigo与System.ServiceModel DLL
然后创建客户端
namespace Client
{
/// <summary>
/// Client定义了一个与Service一样的契约,这个是Client自己定义的,不是引用Service(HelloInDigo类库的)
/// </summary>
[ServiceContract]
public interface IHelloInDigoService
{
[OperationContract]
string Hello(string message);
}
class Program
{
static void Main(string[] args)
{
//通过ChannelFactory创建一个IHelloInDigoService的代理,来访问服务
IHelloInDigoService proxy = ChannelFactory<IHelloInDigoService>.CreateChannel(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:9000/HelloInDigo"));
string s = proxy.Hello("Hello!,我的第一个WCF程序!");
Console.WriteLine(s);
Console.ReadLine();
}
}
}
这样整个程序就创建完毕,运行效果:
首先启动Host,启动成功后,运行Client,得到:
例子下载地址:Hello