配置服务-绑定

一.绑定的概念

 

绑定中的信息可能非常基本,也可能非常复杂。 最基本的绑定仅指定必须用于连接到终结点的传输协议(如 HTTP)。 一般来说,绑定包含的有关如何连接到终结点的信息属于以下类别中的一种。

协议

确定要使用的安全机制:可靠消息传递功能或事务上下文流设置。

编码

确定消息编码(例如,文本或二进制)。

传输

确定要使用的基础传输协议(例如,TCP 或 HTTP)。

 

二.在配置文件中配置绑定

(1).首先我们需要定义一个服务协定ICalculator.cs

 

代码
[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);
}

 

 

(2).建立协定的实现类,我的理解就是行为。

代码
 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;
        }
    }

 

 

(3).现在我们的服务协定定义完了,下面就应该配置我们的服务.

有两种方式

(1)配置文件模式

我们来认识下结构

 

代码
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  
<system.serviceModel>
    
    
<services>
      
      
<!--服务-->
      
<!--name:命名空间+服务协定的实做类-->
      
<service name="ConfigService.CalculatorService" >
        
<!--
        终结点
        1.address 服务地址:http://localhost:8052/MyService
        2.binding 绑定:制定安全模式,传输模式
        3.contract服务协定:也就是公开我们服务所提供的方法
        4.bindingConfiguration:绑定配置文件:也就是说通过这个字段在配置里面找到当前终结点的传输方式
        
-->
        
<endpoint
            
address="http://localhost:8052/MyService"
            binding
="wsHttpBinding"
            bindingConfiguration
="MyBinding"
            contract
="ConfigService.ICalculator" />
      
</service>
      
    
</services>
    
    
<bindings>
      
<!--绑定WebService基础Http绑定-->
      
<wsHttpBinding>
        
<!--name 属性是必须的,通过标记可以使得其他服务访问-->
        
<binding name="MyBinding"
                 closeTimeout
="00:02:00"
                 openTimeout
="00:02:00">
        
</binding>
      
</wsHttpBinding>
    
</bindings>
  
</system.serviceModel>
</configuration>

 

(2)后台代码模式

 

ServiceHost host = new ServiceHost(typeof(CalculatorService));
host.AddServiceEndpoint(
typeof(ICalculator), new BasicHttpBinding(), "http://localhost:8052/MyService");

 

(3)还落下一个,至于缩主,大家就建立一个控制台程序就可以的.

posted @ 2010-10-15 15:51  Bruce T  阅读(269)  评论(0编辑  收藏  举报