我們正在建立一個Windows桌面應用程序(而不是基於Web)並試圖想出實現Repository和UnitOfWork模式的最佳方式。依賴注入
在典型的Asp.Net Mvc應用程序中,您的存儲庫注入了數據上下文,服務注入了存儲庫,最後控制器注入了服務,並且一切都很好,如果您沒有遇到任何異常,您將提交更改。
在windows窗體/ wpf應用程序中,不建議使用單個數據上下文(Oren在MSDN上有一個帖子),因此我們決定在主講人中創建數據上下文。我們正在使用Linq2SQl,我們有兩個不同的數據庫來處理視圖。
目前,我有以下實現
public interface IRepository<T> where T : class
{
IEnumerable<T> Find(Expression<Func<T, bool>> where);
T Single(Expression<Func<T, bool>> where);
...
}
public class Repository<T> : IRepository<T> where T : class
{
private readonly Table<T> _table;
public Repository(DataContext dataContext)
{
_table = dataContext.GetTable<T>();
}
}
public Class TodoService :ITodoService
{
IRepository<Todo> _todoRepository;
public TodoService(DataContext dataContext)
{
_todoRepository = new Repository<Todo>(dataContext)
}
...
}
}
//演示了UI
public class TodoPresenter
{
public void Save()
{
Using (DataContext dataContext = DataContextFactory.GetNewContextForDatabase1())
{
ITodoService service = new TodoService(dataContext);
...
service.Save(..);
dataContext.SubmitChanges();
}
}
}
我想解耦服務演示,並會喜歡在ITodoService被請求時注入TodoService,但我不能注入數據上下文有兩個原因,因爲我必須根據數據庫來決定,或者即使我們只有一個數據庫是Windows應用程序,也不能在應用程序級別維護數據上下文(許多視圖一次打開爲應用程序中的選項卡)並且沒有數據上下文我無法創建存儲庫類並且無法注入服務。
如何在這種情況下,實現解耦任何想法
看看這個:http://bit.ly/bF7jL3。 – Steven 2011-03-03 09:59:35