2014-03-07 29 views
0

我有一個WCF服務接口,看起來像這樣:WCF序列化 - 即時轉換爲不同類型?

[ServiceContract(Namespace = "http://somenamespace", SessionMode = SessionMode.NotAllowed)] 
public interface IRuntimeService 
{ 

    [OperationContract] 
    ISupporterProperties CreateOrModifySupporter(Guid id); 

} 

和實現(客戶端和服務器上)看起來像這樣(其託管並連接到編程):

public IOwnerProperties CreateOrModifyOwner(Guid id) 
{ 

    //get an owner ... 

    //the owner is of type Owner which implements IOwnerProperties. 
    return theOwner; 

} 

但是,問題在於WCF會嘗試將此序列化或反序列化爲Owner,因爲這是返回的實際類型,但我希望它將其作爲OwnerDataContract發送,這也正好實現IOwnerProperties

換句話說,我想返回一個Owner,但將它序列化/反序列化爲OwnerDataContract

我知道我可以爲客戶端界面創建包裝類。但是,我希望儘可能多地使用共享代碼。

回答

1

這是AutoMapper的完美工作。如果OwnerOwnerDataContract具有相同的屬性和字段的設置很簡單,只要

static void Main() 
{ 
    //Do this once at program startup 
    Mapper.CreateMap<Owner, OwnerDataContract>(); 

    //Run the rest of your program. 
} 

如果您需要重新映射因壓扁或重命名將會有更多的設置工作,看到the wiki更多信息的一些屬性。

使用映射它是那樣簡單

public IOwnerProperties CreateOrModifyOwner(Guid id) 
{ 

    //get an owner ... 

    //Mapper.Map retuns a object of type OwnerDataContract 
    return Mapper.Map<OwnerDataContract>(theOwner); 
} 
+0

這很有趣。有沒有使用第三方工具的方法? –

+0

是的,但是那會讓你說你不想做的「爆炸班」。 Automapper通過'Mapper.CreateMap'動態地生成這些包裝 –