2016-03-18 21 views
1

背景:我需要發佈一個簡單的項目,它將用於將數據從我的存儲傳輸到其他地方(其他開發人員將使用我的WCF,WCF將用於傳輸數據(To 。保護DB等),我用蔥架構在我的項目(基礎部分)如何使用DomainModel進入WCF

-------------------------------------- 
|    WCF     | 
| ---------------------------------- | 
| | Interfaces for working with DB | |  
| |  -------------   | | 
| |  |DomainModel|   | | 
| |  -------------   | | 
| -----------------------------------| 
-------------------------------------- 

我展示一個簡單的例子,我的一點改進。

我的DomainModel這樣的:

[DataContract] 
public class User 
{ 
    private string _name; 
    private List<Text> _texts; 

    public User(string name, List<Text> texts) 
    { 
     _name = name; 
     _texts = texts; 
    } 
    [DataMember] 
    public string Name { get { return _name; } } 
    [DataMember] 
    public List<Text> Texts { get { return _texts; } } 
}  


[DataContract] 
public class Text 
{ 
    private string _name; 

    public Text(string name) 
    { 
     _name = name; 
    } 

    [DataMember] 
    public string Name { get { return _name; } } 
} 

WCF服務有這樣的方法:

public DomainModel.User ReturnUser() 
    { 
     User user = new User("Texts", 
      new List<Text>() 
      { 
       new Text("TextOne"), 
       new Text("TextTwo") 
      }); 

     return user; 
    } 

但是當我調用該方法

static void Main(string[] args) 
{ 
    try 
    { 
     ServiceRomanClient client = new ServiceRomanClient(); 
     User user = client.ReturnUser(); 
     Console.WriteLine(user.Name); 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine(ex.Message); 
    } 
} 

我得到這個異常: 這可能是由於服務端點不使用HTTP協議綁定。 這也可能是由於HTTP請求上下文被服務器 中止(可能是由於服務關閉)。查看服務器日誌獲取更多詳細信

如果我的DomainModel這個改變propertis(我增加了設置)

[DataContract] 
public class User 
{ 
    private string _name; 
    private List<Text> _texts; 

    public User(string name, List<Text> texts) 
    { 
     _name = name; 
     _texts = texts; 
    } 
    [DataMember] 
    public string Name { get { return _name; } set{ _name = value; } } 
    [DataMember] 
    public List<Text> Texts { get { return _texts; } set { _texts = value; } } 
} 

[DataContract] 
public class Text 
{ 
    private string _name; 

    public Text(string name) 
    { 
     _name = name; 
    } 

    [DataMember] 
    public string Name { get { return _name; } set{ _name = value;} } 
} 

我不想沒有execption,但我打破S.O.L.I.D principels。

我想不要添加到DomainModel中,我建議解決這個問題的更好方法是在DomainModel和WCF之間創建一個傳輸層。

我會很感激,如果你能給我你的想法從你的經驗。

回答

3

你可以給該物業一個私人二傳手。這樣,數據協定序列化程序仍應能夠序列化對象,但不會將屬性的setter公開給域模型外的任何代碼。

或者,您可以實現一個數據傳輸對象,該對象實際上只是一個具有一羣公共getter和setter的類,並將其用作您的WCF數據契約。我想這個選項的缺點是,你將不得不編寫一些映射代碼或使用自動映射工具來映射域模型和數據傳輸對象。

+0

所以清晰和簡單的解決方案。非常感謝你。我添加了私人設置{_name = value; } –