What are the disadvantages of using static DbConte

2019-06-09 06:06发布

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?

1条回答
一夜七次
2楼-- · 2019-06-09 06:38

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.

查看更多
登录 后发表回答