如何:在代码中创建服务终结点
在本示例中,将为计算器服务定义一个 ICalculator
协定,在 CalculatorService
类中实现该服务,然后在代码中定义其终结点(在这段代码中还指定该服务必须使用 BasicHttpBinding 类)。
通常,最佳做法是以声明方式在配置中指定绑定和地址信息,而不是在代码中强制指定。 在代码中定义终结点通常是不可行的,因为已部署服务的绑定和地址通常与在部署服务时所用的绑定和地址不同。 一般说来,通过将绑定和寻址信息放置在代码之外,无需重新编译或重新部署应用程序即可更改这些信息。
在代码中创建服务终结点
创建定义服务协定的接口。
[ServiceContract] public interface ICalculator { [OperationContract] double Add(double n1, double n2); [OperationContract] double Subtract(double n1, double n2); [OperationContract] double Multiply(double n1, double n2); [OperationContract] double Divide(double n1, double n2); }
<ServiceContract()> _ Public Interface ICalculator <OperationContract()> _ Function Add(ByVal n1 As Double, _ ByVal n2 As Double) As Double <OperationContract()> _ Function Subtract(ByVal n1 As Double, ByVal _ n2 As Double) As Double <OperationContract()> _ Function Multiply(ByVal n1 As Double, _ ByVal n2 As Double) As Double <OperationContract()> _ Function Divide(ByVal n1 As Double, _ ByVal n2 As Double) As Double End Interface
实现在步骤 1 中定义的服务协定。
public class CalculatorService : ICalculator { public double Add(double n1, double n2) { return n1 + n2; } public double Subtract(double n1, double n2) { return n1 - n2; } public double Multiply(double n1, double n2) { return n1 * n2; } public double Divide(double n1, double n2) { return n1 / n2; } }
Public Class CalculatorService Implements ICalculator Public Function Add(ByVal n1 As Double, _ ByVal n2 As Double) As Double Implements ICalculator.Add Return n1 + n2 End Function Public Function Subtract(ByVal n1 As Double, _ ByVal n2 As Double) As Double Implements ICalculator.Subtract Return n1 - n2 End Function Public Function Multiply(ByVal n1 As Double, _ ByVal n2 As Double) As Double Implements ICalculator.Multiply Return n1 * n2 End Function Public Function Divide(ByVal n1 As Double, _ ByVal n2 As Double) As Double Implements ICalculator.Divide Return n1 / n2 End Function End Class
在主机应用程序中,创建该服务的基址以及要用于该服务的绑定。
// Specify a base address for the service String baseAddress = "http://localhost/CalculatorService"; // Create the binding to be used by the service. BasicHttpBinding binding1 = new BasicHttpBinding();
' Specify a base address for the service Dim baseAddress = "http://localhost/CalculatorService" ' Create the binding to be used by the service. Dim binding1 As New BasicHttpBinding()
创建宿主并调用 ServiceHost.AddServiceEndpoint(Type, Binding, String) 或其他重载之一来添加宿主的服务终结点。
using(ServiceHost host = new ServiceHost(typeof(CalculatorService))) { host.AddServiceEndpoint(typeof(ICalculator),binding1, baseAddress);
Using host As New ServiceHost(GetType(CalculatorService)) With host .AddServiceEndpoint(GetType(ICalculator), _ binding1, _ baseAddress)
若要在代码中指定绑定,而不使用运行时提供的默认终结点,请在创建 ServiceHost 时将基址传递给构造函数,并且不调用 ServiceHost.AddServiceEndpoint。
ServiceHost host = new ServiceHost(typeof(CalculatorService), new Uri(baseAddress));
Dim host As New ServiceHost(GetType(CalculatorService), New Uri(baseAddress))
有关默认终结点的详细信息,请参阅简化配置和 WCF 服务的简化配置。