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.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 定義一個命名空間(命名空間的好處就不用多說了),象下面這樣:
public interface IAnrsServiceContract1
如果沒有明確指定命名空間,WCF 會爲
ServiceContract 指定一個默認的命名空間 http://tempuri.org
。ServiceContract 的名字最好和接口的名字相同。
public interface IAnrsServiceContract1
同樣的,也可以爲 OperationContract 指定名字。
public interface IAnrsServiceContract1
{
[OperationContract(Name = " GetFullName " )]
string GetFullName( string author);