0

我認爲我在我的正在進行的web項目中有一些設計錯誤(我正在使用Linq2SQL實現存儲庫模式) 1)每個存儲庫創建自己的DataContext(這是否正確?是否應該這樣) 例如:存儲庫設計問題

public class SQLPersonRepository : IPersonRepository 
{ 
    DataContext dc; 

    public SQLPersonRepository(string connectionString) 
    { 

     dc = new DataContext(connectionString, Mapping.GetMapping()); 

     personTable = (dc).GetTable<Person>(); 
     personRoleTable = (dc).GetTable<PersonRole>(); 
     roleTable = (dc).GetTable<Role>(); 

    } 
    Get Method 
    Add Methods for the different Tables 
    Save Method 
} 

和另一個例子:

class SQLTrainingCenterRepository:ITrainingCenterRepository 
    { 
     DataContext dc; 
     private Table<Trainingcenter> trainingCenterTable; 

    public SQLTrainingCenterRepository(string connectionString) 
     {    
      dc = new DataContext(connectionString, Mapping.GetMapping()); 

      trainingCenterTable = (dc).GetTable<Trainingcenter>();    
     } 

     Get Methods 
     Add Method 
     Save Method   
} 

正如你可以計算出我使用的IoC(溫莎,使用生活方式= 「PerWebRequest」)。

2)爲每個存儲庫使用服務層。例如。對於人

public class PersonBusinessLayer 
{ 
    IPersonRepository personRepository; 

    public PersonBusinessLayer(IPersonRepository personRepository) 
    { 
     this.personRepository = personRepository; 

    } 
    ... diverse Get Methods 
    Add Method (wrapper around repository.Add) 
    Save Method (wrapper around repository.Save) 
} 

這是定義服務層的正確方法嗎?或者我應該使用一個引用所有存儲庫的服務類?

3)personTable和trainingCenterTable之間有關係。每當我向TrainingCenter-Service插入內容時,我也必須在Person-Service中插入一條記錄。因此,解決的辦法是說:

TrainingCenterBusinessLayer.Insert(trainingCenter); 
PersonBusinessLayer.Insert(person); 

我當然希望這兩個插入等事務的方式發生的事情,所以我決定把這個包報表

using (TransactionScope scope = new TransactionScope()) 
{ 
... 
} 

所以有出現了新的問題:服務器上的MSDTC'。\ SQLEXPRESS'不可用(因爲有不同的DataContexts,對嗎?)。如何克服這個?!?

解決方法是從外部創建DataContext並將其作爲參數傳遞給存儲庫!正確的思想?但如何實施?

4)使用現有的設計,我必須打電話給: TrainingCenterBusinessLayer.Save(); PersonBusinessLayer.Save(); 我認爲這是錯誤的! save()操作應該在DataContext中調用一次。但是如何? (顯然這可以通過解決上述問題來解決)。

回答

0

如果你正在做全對DI,你應該嘗試繞過的抽象(接口)作爲依賴。這樣,如果你想嘲笑它,你可以輕鬆地換掉它的實現。

DataContext可以傳遞,但也許有點沉重。更好的選擇IMO將是IDbConnection

連接字符串不是真的依賴關係,它是用於初始化依賴項的特定實現的參數。

還有MvcFakes方法與IDataContext和上下文包裝,但我覺得這是一個痛苦。只要您的DataContext實例共享相同的連接實例,則不需要分佈式事務。