EF and repository pattern - ending up with multiple DbContexts in one controller - any issues (performance, data integrity)?

后端 未结 3 718
一个人的身影
一个人的身影 2020-12-28 10:37

Most of my knowledge of ASP.NET MVC 3 comes from reading through the book Pro ASP.NET MVC 3 Framework by Adam Freeman and Steven Senderson. For my test application I have tr

3条回答
  •  别那么骄傲
    2020-12-28 10:53

    Do I risk ending up with multiple DbContexts within one request?

    Yes. Each instance of a repository is going to instantiate its own DbContexts instances. Depending on the size and use of the application, this may not be a problem although it is not a very scalable approach. There are several ways of handling this though. In my web projects I add the DbContext(s) to the Request's Context.Item collection, this way it is available to all classes that require it. I use Autofac (similar to Ninject) to control what DbContexts are created within specific scenarios and how they are stored, e.g. I have a different 'session manager' for a WCF context to the one for a Http context.

    And would that lead to any significant performance overhead?

    Yes, but again not massively if the application is relatively small. As it grows though, you may notice the overhead.

    How about a potential for conflicts between the contexts and any consequences to the data integrity?

    One of the reasons for using an ORM like this is so that changes can be maintained within the DbContext. If you are instantiating multiple context instances per request you lose this benefit. You wouldn't notice conflicts or any impact of the integrity per se unless you were handling a lot of updates asynchronously.

提交回复
热议问题