[WCF] Service contract

using  System;
using  System.ServiceModel;

namespace  Anrs.Service
{
    [ServiceContract()]
    
public   interface  IAnrsServiceContract
    {
        [OperationContract()]
        
string  GetFullName( string  author);

        [OperationContract()]
        
string  GetFamilyName( string  author);
    }

    
public   class  AnrsService : IAnrsServiceContract
    {
        
public   string  GetFullName( string  author)
        {
            
return  author.Replace( ' . ' '   ' );
        }

        
public   string  GetFamilyName( string  author)
        {
            
return  author.Split( ' . ' )[ 2 ];
        }
    }
}

服务契约映射到 CLR 接口类型,并且对于契约来讲,可访问性是无关紧要的,因为“可访问性”本身就是一个 CLR 的概念,在 WCF 中是不存在该概念的。没有实现  ServiceContract 特性的接口对客户端就是不可见的,这就暗合了 SO 的“边界清晰”原则。另外,必须明确告诉 WCF 那些方法是 ServiceContract 的一部分(使用 OperationContract 特性,没有应用 OperationContract 特性的方法将不被视为服务契约的一部分),也就是说这些方法能够被客户端调用。不过,OperationContract 特性只能应用到方法上,对 properties/indexers/events 来讲都是无效的。

单个方法也可以实现多个应用了 ServiceContract 特性的接口。

using  System;
using  System.ServiceModel;

namespace  Anrs.Service
{
    [ServiceContract()]
    
public   interface  IAnrsServiceContract1
    {
        [OperationContract()]
        
string  GetFullName( string  author);

        [OperationContract()]
        
string  GetFamilyName( string  author);
    }

    [ServiceContract()]
    
public   interface  IAnrsServiceContract2
    {
        [OperationContract()]
        
void  SaveAuthor( string  author);
    }

    
public   class  AnrsService : IAnrsServiceContract1, IAnrsServiceContract2
    {
        
public   string  GetFullName( string  author)
        {
            
return  author.Replace( ' . ' '   ' );
        }

        
public   string  GetFamilyName( string  author)
        {
            
return  author.Split( ' . ' )[ 2 ];
        }

        
public   void  SaveAuthor( string  author)
        {
            Console.WriteLine(
" Save {0} to database " , author);
        }
    }
}
 

名字 1 和命名空间

可以也应该为 ServiceContract 定义一个命名空间(命名空间的好处就不用多说了),象下面这样:

[ServiceContract(Namespace = " Anrs.Service " )]
public   interface  IAnrsServiceContract1


如果没有明确指定命名空间,WCF 会为 ServiceContract 指定一个默认的命名空间 http://tempuri.org 。ServiceContract 的名字最好和接口的名字相同。

[ServiceContract(Namespace = " Anrs.Service " , Name = " IAnrsServiceContract1 " )]
public   interface  IAnrsServiceContract1


同样的,也可以为 OperationContract 指定名字。

 

    [ServiceContract(Namespace = " Anrs.Service " , Name = " IAnrsServiceContract1 " )]
    
public   interface  IAnrsServiceContract1
    {
        [OperationContract(Name
= " GetFullName " )]
        
string  GetFullName( string  author);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值