C# EF6 make multiple async calls to one context using Unity - Asp.Net Web Api

拜拜、爱过 提交于 2019-12-24 12:23:43

问题


I get the following error when visiting my SPA site which makes some calls to the API when loaded:

A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe.

If I don't use the same context and try to update values I get the following error, see this question:

Entity Framework 6 - Dependency Injection with Unity - Repository pattern - Add or Update exception for many to many relationship

The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.

This means that I can't use the answer suggested here to use multiple contexts:

https://stackoverflow.com/a/20635076/3850405

UnityConfig.cs:

container.RegisterType<DbContext>(new HierarchicalLifetimeManager());
container.RegisterType<ISupplierRepository, SupplierRepository>();
container.RegisterType<IContactRepository, ContactRepository>();

How can I solve this?


回答1:


Solved it with PerRequestLifetimeManager from Microsoft.Practices.Unity.Mvc.

container.RegisterType<DbContext>(new PerRequestLifetimeManager());
container.RegisterType<ISupplierRepository, SupplierRepository>();
container.RegisterType<IContactRepository, ContactRepository>();


来源:https://stackoverflow.com/questions/45146126/c-sharp-ef6-make-multiple-async-calls-to-one-context-using-unity-asp-net-web-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!