3.实现服务契约
我们已经有了服务契约,现在是创建真正的服务的时候了。这很简单,只要实现服务契约的接口就可以了。
添加实体类
(1)在项目中添加一个名为Calculator.cs的新文件。
具体步骤:
·选择Project | Add Class菜单项。
·在Add New Item对话框中,将Name设为Calculator.cs。
·单击Add按钮。
(2)打开新添加的类文件。
(3)加入一行using语句来导入System.ServiceModel名字空间。
(4)给类加上public 修饰符。
(5)类文件现在看起来应该像下面这样:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace DerivativesCalculatorService
{
public class Calculator
{
}
}
实现服务契约的接口
(6)在类定义的后面加上: IDerivativesCalculator。
(7)按快捷键Shift + ALT + F10,这会弹出一个菜单来帮助我们实现接口,如图所示。

图3 实现一个接口
(8)选择Implement interface ‘IDerivitivesCalculator’菜单项,Visual Studio会为我们添加代码来实现接口。
(9)类的代码现在看起来应该像下面这样:
{
#region IDerivativesCalculator Members
public decimal CalculateDerivative(int days, string[] symbols,
string[] functions)
{
throw new NotImplementedException();
}
#endregion
}
因为这个实验的重点并不是实现具体的业务逻辑,所以在这个简单的实验中,我们只是从函数中返回一个值。
(10)用下面的代码替换掉NotImplementedException。
public decimal CalculateDerivative(int days, string[] symbols, string[] functions)
{
return (decimal) (System.DateTime.Now.Millisecond);
}
(11)保存类文件(选择File | Save All菜单项或按快捷键CTRL + S)
这就是前面定义的服务契约的完整实现。
构建项目
(12)选择Build | Build Solution菜单项。
(13)如果项目在构建时没有产生错误,那么我们就完成了Derivatives Calculator服务的实现。