0

說我有一個GenericRepository:C#MVC庫繼承和共同的DataContext

public class IGenericRepository 
{ 
    // bla bla bla 
} 

public class GenericRepository : IGenericRepository 
{ 
    public myDataContext dc = new myDataContext(); 

    // bla bla bla 
} 

和我有類特定的資源庫:

public class CategoryRepository : GenericRepository 
{ 
    // bla bla bla 
} 

,並在我的控制器:

public ActionResult something() 
{ 
    CategoryRepository cr = new CategoryRepository(); 
    GenericRepository gr = new GenericRepository(); 
    Category cat = cr.GetMostUsedCategory(); 
    SubCategory sub = gr.GetById(15); 

    // And after I make some changes on these two entities I have to: 

    cr.Save(); 
    gr.Save(); 
} 

現在,是否可以使用適用於所有存儲庫的通用數據環境?所以,當我從gr.Save()保存它將申請cr?我的意思是:

//Instead of 
cr.Save(); 
gr.Save(); 

//I want 
gr.Save(); // And my category will also be saved. 

這可能嗎?

回答

0

你能做這樣的事嗎? (將您的派生存儲庫傳遞給泛型)

public class IGenericRepository 
{ 
    void Save(); 
} 

public class GenericRepository : IGenericRepository 
{  
    public myDataContext dc = new myDataContext(); 
    private _IGenericRepository = null; 

    // bla bla bla 

    public GenericRepository(IGenericRepository repository) 
    { 
     _IGenericRepository = repository; 
    } 

    void Save() 
    { 
     _IGenericRepository.Save(); 
    }   
} 
0

IGenericRepository包含您的保存方法嗎?

public class IGenericRepository 
{ 
    save{}; 
} 
0

在你的情況在這裏假定CategoryRepository從GenericRepository繼承爲什麼不使用兩個電話和therfore相同的上下文中CategoryRepository。然而,最好的方法是通過DI容器注入上下文,並使用容器的LifetimeManager來確保整個HttpRequest具有相同的上下文。

如果你碰巧使用微軟的團結,我寫了一篇博客文章對此here

+0

好吧,你是對的,對於這個例子我可以做到這一點,但有些情況下我必須使用不同的特定存儲庫,那麼我應該在那裏做什麼? – Shaokan

+0

如果將相同的上下文注入到兩個存儲庫中,則調用Save將導致期望的行爲。然而,通過通過接口抽象上下文,這種模式(工作單元)變得更加明確。然後,您的控制器也將依賴此接口並決定何時調用Save。由於此接口解析爲傳遞到兩個存儲庫的上下文,因此您將獲得所需的行爲。 –

0

可以使用Unit Of work模式爲這些目的。在你的倉庫

//It is the generic datacontext 
public interface IDataContext 
{ 
    void Save(); 
} 

//It is an implementation of the datacontext. You will 
//have one of this class per datacontext 
public class MyDataContext:IDataContext 
{ 
    private DataContext _datacontext; 
    public MyDataContext(DataContext dataContext) 
    { 
     _datacontext = dataContext; 
    } 

    public void Save() 
    { 
     _datacontext.Save(); 
    } 
} 

然後:

0

您應該添加一個抽象層以上的DataContext的概念

public class GenericRepository<TDataContext> : IGenericRepository where TDataContext: IDataContext,new() 
{ 
    public TDataContext dc = new TDataContext(); 

    // bla bla bla 
} 

public class CategoryRepository:GenericRepository<MyDataContext> 
{ 
    // bla bla bla 
    public void SaveSomething() 
    { 
     dc.Save(); 
    } 
} 

當然,這只是一段路要走:-)你可以改進它,但重點是抽象Datacontext的概念。您可以將您的代碼用於任何數據上下文(即使是NHibernate)。