What are the disadvantages of using static DbContext?

Technology CommunityCategory: Entity FrameworkWhat are the disadvantages of using static DbContext?
VietMX Staff asked 3 years ago
  • Since DbContext is not thread safe, if your application have async action then it’s possible to have multiple thread using your DbContext, which can lead to an exception.
  • On another hand, creating a new DbContext instance doesn’t mean open a new connection to DB. Net Framework should use one of connections already open in Connection Pool.
  • If you only use one DbContext instance and lock it for thread safety, so you only have one connection to DB. If your website have hundreds of request per second then all of them have to queue to use the only connection. In that case, DbContext object became the perfomance bottleneck of your system. And there are tons of problem with data caching in EF when you working with static DbContext instance.

So, it’s better to create a new instance of DbContext for each request – let the framework manage the connection for us and don’t worry it should fast.