0

I am new to Visual Studio. I am developing a MVC web project and I'm using static DbContext. Because it is not a simple web page when a user sign in, he will use the program for a long time and I want it to be fast. What are the disadvantages of using static DbContext?

jsanalytics
  • 13,058
  • 4
  • 22
  • 43
tgrl-66
  • 1
  • 3
  • I think the reason your login is slow is because the server had to initialize the database. Try to run the login system multiple times in one session and report if the speed is still the same. If I am right the system will run slow when using it for the first time, but after that it would run faster. – Hugo Woesthuis Nov 18 '17 at 12:58
  • 2
    Possible duplicate of [Entity framework context as static](https://stackoverflow.com/questions/888185/entity-framework-context-as-static) – Federico Dipuma Nov 18 '17 at 13:29

1 Answers1

2

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.

Sy Le
  • 133
  • 8