Appropriate Repository LifeCycle Scope w/ Ninject in MVC

后端 未结 2 1429
天涯浪人
天涯浪人 2021-02-10 01:51

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 defa

2条回答
  •  不思量自难忘°
    2021-02-10 02:35

    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(id);
        entity.Prop = "Processing";
        _module.DoStuff(id);
    }
    

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

提交回复
热议问题