1

I'm using Entity Framework (code first), Repositories, and the Unit of Work pattern, essentially as described here: Entity Framework 4 CTP 4 / CTP 5 Generic Repository Pattern and Unit Testable

I'm also using StructureMap to manage my object instances and I have some code like this wiring up the EF dbcontext and unit of work:

    For<DbContext>().HybridHttpOrThreadLocalScoped().Use<MyDbContext>();
    For<IUnitOfWork>().HybridHttpOrThreadLocalScoped().Use<UnitOfWork>();

I also have a generic Repository<T> that currently knows about the MyDbContext instance. Now I need to be able to support multiple databases, and thus multiple DbContexts. I'm considering trying to adjust my IUnitOfWork to be instead an IUnitOfWork<T>, where T is the DbContext to use. But my repository will also need to know which DbContext to use, so do I then have to make it doubly generic (e.g. Repository<TEntity,TDbContext>)?

What's the best, simplest way to support multiple databases using the UnitOfWork pattern I'm using?

Community
  • 1
  • 1
ssmith
  • 8,092
  • 6
  • 52
  • 93

1 Answers1

0

It depends on your application logic. Are you going to do changes in multiple databases withing single unit of work? If yes you should still use one unit of work with database factory for each database accessed within that unit of work. Commit of that unit of work should use TransactionScope to make changes in all database atomically (this can be little bit more challenging).

If you always need to make changes only in a single database you can use single generic unit of work but you also have to implement generic Get on database factory. Passing context type to the repository is not needed. Move the initialization logic to concrete repositories which know the type of context they must use and they will ask database factory for that context.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • I don't expect to need to do anything across multiple DbContexts. If I do, I can fall back to my own implementation of transactions, etc, or figure something else out. But for the purposes of this question, assume that's never happening. – ssmith Sep 02 '11 at 02:08