本示例程序演示如何编写一个简单的WCF 示例程序。
如何使用WCF 示例代码:
Server 端:Console 程序,WCF Service 承载在Console 程序中。
[ServiceContract(Namespace = "[url]http://microsoft.servicemodel.samples/[/url]")]
public interface IBankService
{
[OperationContract]
int AddAccount(string clientName, int clientAge);
[OperationContract]
bool RemoveAccount(int accountNumber);
[OperationContract]
List<String> GetAccounts();
}
class BankService: IBankService
{
private List<Account> _accounts = new List<Account>();
private int _idGenerator = 0;
{
Console.WriteLine(OperationContext.Current.SessionId);
Account acc = new Account(_idGenerator, clientName, clientAge);
_accounts.Add(acc);
Console.WriteLine("ADD - " + acc.ToString());
return _idGenerator;
}
......
Client 端: 也是一个Console 程序,负责调用/测试 WCF Services。
using (ChannelFactory<IBankService> bankFactory =
new ChannelFactory<IBankService>("MyClient"))
{
IBankService bankProxy = bankFactory.CreateChannel();
bankProxy.AddAccount("John", 20);
Console.WriteLine("Adding Peter , 21 years");
bankProxy.AddAccount("Peter", 21);
Console.WriteLine("Adding Andrew , 25 years");
bankProxy.AddAccount("Andrew", 25);
bankProxy.RemoveAccount(1);
Console.WriteLine();
Console.WriteLine("Press <Enter> to close");
Console.ReadLine();
}
运行WCF 示例项目:
启动WCF Server 端 Console 程序,运行界面如下:

下面是通过C# Application 调用上述WCF Service 的运行情况:

恭喜!你现在已经完成了一个WCF Service 程序!
















