2.定义服务契约
(1)将Class1.cs更名为IDerivativesCalculator.cs
具体步骤:
·在Solution Explorer的DerivativesCalculatorService项目中,鼠标右键单击Class1.cs并选择Rename菜单项。
·输入IDerivativesCalculator.cs。
·当Visual Studio弹出确认窗口时选择Yes。
(2)打开IDerivativesCalculator.cs代码文件。它的内容应该像下面这样:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DerivativesCalculatorService
{
public class IDerivativesCalculator
{
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DerivativesCalculatorService
{
public class IDerivativesCalculator
{
}
}
(3)删除文件中的所有代码。
(4)在空白文件中插入下面的代码段。这等于是对代码做以下修改:
·添加了导入System.ServiceModel名字空间的using语句。
·将类声明为公有的。
·将IDerivativesCalculator从类改为接口。
·在接口上使用ServiceContract attribute。
这样做是为了告诉WCF运行库,该接口是一个WCF服务契约。这是定义WCF服务的关键步骤。
SnippetWCF-Intro-1
using System;
using System.ServiceModel;
namespace DerivativesCalculatorService
{
[ServiceContract]
public interface IDerivativesCalculator
{
}
}
using System;
using System.ServiceModel;
namespace DerivativesCalculatorService
{
[ServiceContract]
public interface IDerivativesCalculator
{
}
}
(5)在接口中加入下面的方法:
SnippetWCF-Intro-2
[ServiceContract]
public interface IDerivativesCalculator
{
Decimal CalculateDerivative(int days, string[] symbols, string[] functions);
}
[ServiceContract]
public interface IDerivativesCalculator
{
Decimal CalculateDerivative(int days, string[] symbols, string[] functions);
}
虽然我们已经定义了接口中必须实现的一个方法,但除非在方法上使用相应的attribute,否则WCF运行库是认不出这个方法的。
(6) 在接口的方法定义上使用OperationContract attribute。
这样做是为了告诉WCF运行库,这个方法定义了一个操作,在这个服务契约的任何实现中都可以使用。
(7)现在的代码看起来如下所示。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace DerivativesCalculatorService
{
[ServiceContract]
public interface IDerivativesCalculator
{
[OperationContract]
Decimal CalculateDerivative(int days, string[] symbols,
string[] functions);
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace DerivativesCalculatorService
{
[ServiceContract]
public interface IDerivativesCalculator
{
[OperationContract]
Decimal CalculateDerivative(int days, string[] symbols,
string[] functions);
}
}
现在我们已经定义了一个简单的WCF契约。
就这么简单!