Appropriate Repository LifeCycle Scope w/ Ninject in MVC

风流意气都作罢 提交于 2019-12-21 02:35:22

问题


What is the appropriate LifeCycle Scope for a repository and the EF context when using Entity Framework 4 with Ninject in an MVC 3 application?

I've been using the default of InTransientScope, but questioning whether it should be InRequestScope.

 public class MyController: Controller
 {
   private readonly IMyRepo _repo;
   public MyController(IMyRepo repo)
   {
     _repo = repo;
   }

   public ActionResult Index()
   {
     var results = _repo.GetStuff();
     return View(results);
   }
 }

Ninject Module:

  public class MyServices : NinjectModule
  {
    public overrride void Load()
    {
      Bind<IMyRepo>.To<MyRepo>();
      Bind<MyContext>.ToSelf();
    }
  }

MyRepo:

public class MyRepo: IMyRepo
{
  private readonly MyContext _context;
  public MyRepo(MyContext context)
  {
    _context = context;
  }
  public IEnumerable GetStuff()
  {
    return _context.Entity;//query stuff
  }

}

回答1:


Your repository can be transient scope, however, I would bind the context in request scope. This way all of your repository instances will share the same context. This way you can reap the caching and transactional benefits of an ORM.

The way it works currently in your code is that a new context is created any time you request one. So if your controller first uses a repository and then calls another module that in turn uses a repository. Each of those repositories will have a different instance of the context. So in effect you are now using your ORM simply as a connection manager and SQL generator.

This can also have unintended consequences. Imagine a code like the following:

public ActionResult MyAction(int id)
{
    var entity = _repository.Get<Entity>(id);
    entity.Prop = "Processing";
    _module.DoStuff(id);
}

If the DoStuff method, eventually calls _repository.Get<Entity>(id); again, you will have 2 different copies of your entity that are out of sync.




回答2:


This depends on a couple of factors.

  1. Do you care about transactions at all? It not that transient scope is ok for you.

  2. Do you care about transactions but think one transaction per web request is ok for you? Then use web scoped.

  3. Are you ok with objects being "cached" in EF's context and don't want a full database refresh if you request the same object twice? Web scope has this side effect.



来源:https://stackoverflow.com/questions/5266821/appropriate-repository-lifecycle-scope-w-ninject-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!