We are builing a windows desktop application (not web based) and trying to come up with the best way to implement Repository and UnitOfWork Pattern.
In a typical Asp.Net Mvc application your repositories are injected with data context, services are injected with repositories and finally controllers are injected with services and all is well if you don't hit any exception, you will commit the changes.
In windows forms/wpf applications it is not advisable to use single datacontext ( Oren has a post on this on MSDN) so we have decided to create data context at the presenter. We are using Linq2SQl and we have two different databases to work with based on the view.
Currently I have the following implementation
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)
}
...
}
}
// Presenter for the UI
public class TodoPresenter
{
public void Save()
{
Using (DataContext dataContext = DataContextFactory.GetNewContextForDatabase1())
{
ITodoService service = new TodoService(dataContext);
...
service.Save(..);
dataContext.SubmitChanges();
}
}
}
I would like decouple the presenter from service and would like to inject TodoService when ITodoService is requested, but I cannot inject data context for two reasons, as I have to decide based on the database or can't even maintain a data context at the application level even if we have only one database being a windows application (many views are open at a time as tabs in the app) and with no data context I cannot create Repository classes and can't inject services.
Any idea on how to achieve decoupling in this situation
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…