EntityFramework DbContext lifecycle + Postgres: “An operation is already in progress.”

后端 未结 1 1224
慢半拍i
慢半拍i 2020-12-21 06:59

I have been messing with the following for a few days now.

I have a Nancy app running on Mono, with EntityFramework with Repository pattern and UnitOfWork, and Postg

相关标签:
1条回答
  • 2020-12-21 07:38

    Will a bit expand my comments for future reference of people who might have the same error. As you probably know already, Entity Framework's DbContext follows so called "unit of work" pattern, which means you have to use one instance for one logical piece (unit) of work. Reusing the same instance for multiple units of work is not desired, and in some cases like this may even lead to failures. Unlike SQL Server, Postgresql does not support MARS (Multiple Active Result Sets), which means it does not support executing multiple commands over the same connection at the same time. When you reuse single instance of DbContext from multiple threads, they reusing the same underlying sql connection when executing their commands, which leads to the error above.

    As stated in comments, the way to resolve the issue is always create new instance of DbContext for every operation, and dispose it afterwards. This means registering it as

    container.Register<IReflectDbContext, ReflectDbContext> ().AsMultiInstance();
    

    And ensure that you never store DbConext instance in a static field \ singleton instance of another class (for example your ReflectUnitOfWork is singleton, and if you store DbContext in a field there - same problem again).

    0 讨论(0)
提交回复
热议问题