本文主要是介绍WCF学习笔记(二),服务契约,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、服务契约介绍
我个人理解服务契约是一组公开的操作,其中公开的操作(OperationContract)只能定义在方法(Method)上。对于我们要公开的服务我们可以在接口或者类上加上标识ServiceContract。但是我们一般情况下,会把ServiceContract定义在接口上而不是类上,这样有几个好处:
1.方便契约的继承,不同的类型可以去实现相同的契约,重用性高。
2.同一服务可以去实现多个契约。
3.可以随时去修改服务类型,而不需去修改接口。
下面定义一个服务的契约:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace Service
{
[ServiceContract(Name="Service_Calucator",Namespace="Henllyee")]
public interface ICalucator
{
[OperationContract]
int Add(int x, int y);

}
}
我们在上面首先定义了一个接口名称为:ICalucator,然后我们要将这个接口公开为服务契约在上面加上属性标识[ServiceContract],其中Name可以为契约指定别名,这样的话,如果我们在客户端遇到相同的接口时可以通过Name来制定别名区别开来。公开的操作为Add方法,在上面标识[OperationContract]即可。
二、方法的重载
按照我们正常的方法去重载的话,只需要方法的参数不同(个数、类型)就可以实现方法的重载。但是我们在服务契约的定义的时候是不能怎样的,wdsl是编译同不过的如:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace Service
{
[ServiceContract(Name="Service_Calucator",Namespace="Henllyee")]
public interface ICalucator
{
[OperationContract]
int Add(int x, int y);

[OperationContract]
double Add(double x, double y);
}
}
上面的方法是编译不能通过的。但是我们有一种解决的办法可以去解决这样的问题,就是通过OperationContract的Name属性来设定方法的别名是实现方法的重载。如:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace Service
{
[ServiceContract(Name="Service_Calucator",Namespace="Henllyee")]
public interface ICalucator
{
[OperationContract(Name="IntAdd")]
int Add(int x, int y);

[OperationContract(Name="DoubleAdd")]
double Add(double x, double y);
}
}
下面我们通过数据元的方式来配置一个宿主主机,我们添加一个控制台的程序,通过配置App.Config来实现。
在App.Config中:
xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service name="Service.Calucator" behaviorConfiguration="mex">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8888"/>
baseAddresses>
host>
<endpoint address="Calucator" binding="basicHttpBinding" contract="Service.ICalucator"> endpoint>
service>
services>
<behaviors>
<serviceBehaviors>
<behavior name="mex">
<serviceMetadata httpGetEnabled="true"/>
behavior>
serviceBehaviors>
behaviors>
system.serviceModel>
configuration>
在主程序中:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Service;

namespace Host
{
class Program
{
static void Main(string[] args)
{
ServiceHost host = null;
try
{
host = new ServiceHost(typeof(Calucator));
host.Open();

Console.Write("Host is opening now! Press any key to stop");
Console.Read();
}
finally
{
host.Close();
}
}
}
}
然后我们启动主机,在浏览器中输入地址:http://www.systhinker.com/?wsdl 。我们可以看到:

我们可以看到wsdl编译时已经将名称编译成为了我们Name中定义的别名。
WCF学习笔记系列链接:
WCF学习笔记(一),WCF预览
WCF学习笔记(二),服务契约
WCF学习笔记(三),数据契约
WCF学习笔记(四),数据契约的事件
WCF学习笔记(五),数据契约的已知类型
WCF学习笔记(六),实例类型
这篇关于WCF学习笔记(二),服务契约的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!