我们正在建立一个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