1

I'm using EF 4.3 in an MVC4 application and Ninject.MVC3. Controllers are MVCscaffolded using the -Repository switch. The MVCScaffolder creates repository classes (and corresponding IRepository interfaces) using EF for data access in which the DbContext derived object is always "newed" up as a data member in each scaffolded repository.

MyContext context = new MyContext();

The nature of scaffolding a controller is such that for each controller, you typically also get a corresponding repository.

Questions:

1) Does it make sense to have a repository for each domain object that you have a controller for? This seems counterintuitive compared to the repository pattern where only aggregate roots should
be exposed.

2) Does it make sense to have a new instances of a DbContext derived object generated everytime a repository object is instantiated or does it make sense to have a singleton instance of the DbContext derived object registered with the DI container on app startup and resolve it in the singleton repositories like so:

Bind<MyContext>().To<MyContext>().InSingletonScope();  //ninject code on app startup


 //resolve context in repositories: 
 MyContext context = ServiceLocator.Current.GetInstance<MyContext>();

Are there any downsides to holding on to a DbContext derived object as a singleton for the lifetime of the application?

Thanks.

Abhijeet Patel
  • 5,904
  • 7
  • 46
  • 90

1 Answers1

2
  1. It depends what you expect. If you want to use real repository you will use aggregate roots and you will write those repositories yourselves (no automatic generation) because such repository is always specific. If you just want generic wrapper around EF you will use your current solution. T
  2. Normally new context is used per HTTP request for scenarios where your controller must use more than one repository and have to coordinate saving data in all repositories together (unit of work pattern). Don't use singleton context!
Community
  • 1
  • 1
Ladislav Mrnka
  • 349,807
  • 56
  • 643
  • 654