EF context management

What is the best way to manage Entity Framework context when using an MVC application?

I am using a repository / service template.

Edit

After looking at some of these questions: stackoverflow.com/users/587920/sam-striano, I'm more confused than before. Some say that use context for each repository, but wht if I want to use multiple repositories in one controller method?

And to follow a good separation design, how do you use UnitOfWork in an MVC application without making it depend on EF? I want unit test my controllers, model, services, etc. Using context layout?

+7
source share
2 answers

Use dependency injector / inversion of control structure, for example:

  • Ninject
  • Autofac
  • Structuremap
  • Unity

Using the IoC container, you can specify how to manage a single data context (most often for each request). When you set the data context for each request, the container automatically sets up any class that needs the data context, the same data context for each request.

Here is a good article on configuring Ninject.

Most likely, your code will look if you use a common repository:

Ninject module:

public class NinjectRegistrationModule : NinjectModule { public override void Load() { Bind<MyDataContext>().ToSelf().InRequestScope(); Bind(typeof(RepositoryImplementation<>)).ToSelf().InRequestScope(); } } 

General repository:

 public RepositoryImplementation<T> : IRepository<T> where T : class { MyDataContext _dataContext; public RepositoryImplementation<T>(MyDataContext dataContext) { _dataContext = dataContext; } // bunch of methods that utilize _dataContext } 

Class of service:

 public class MyServiceClass { IRepository<SomeEntity> _someEntityRepository; public MyServiceClass(IRepository<SomeEntity> someEntityRepository) { _someEntityRepository = someEntityRepository; } // do stuff with _someEntityRepository = someEntityRepository; } 

Controller:

 public class MyController { MyServiceClass _myServiceClass; public MyController(MyServiceClass myServiceClass) { // Ninject will auto-magically give us a myServiceClass // which will Ninject will inject a repository into MyServiceClass constructor _myServiceClass = myServiceClass; } public ActionResult MyAction() { // use _myServiceClass to do stuff return View(); } } 
+6
source

If your functionality is straightforward, then you must create a new ObjectContext in each repository. They are cheap to create instances.

If this creates a conflict, you can use the Unit of Work template, as suggested in the comment.

I would advise you to be especially careful when integrating an ObjectContext or DataContext with a DI container. By default, many of them do not use the appropriate framework for their life cycle.

0
source

All Articles