简体   繁体   English

C#EF6使用Unity对一个上下文进行多个异步调用-Asp.Net Web Api

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

I get the following error when visiting my SPA site which makes some calls to the API when loaded: 访问我的SPA网站时,出现以下错误,该网站在加载时会对该API进行一些调用:

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. 使用“ await”来确保在此上下文上调用另一个方法之前,所有异步操作都已完成。 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 实体框架6-具有Unity的依赖项注入-存储库模式-多对多关系的添加或更新异常

The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects. 无法定义两个对象之间的关系,因为它们已附加到不同的ObjectContext对象。

This means that I can't use the answer suggested here to use multiple contexts: 这意味着我不能使用此处建议的答案来使用多个上下文:

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

UnityConfig.cs: UnityConfig.cs:

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

How can I solve this? 我该如何解决?

Solved it with PerRequestLifetimeManager from Microsoft.Practices.Unity.Mvc . 使用Microsoft.Practices.Unity.Mvc PerRequestLifetimeManager解决了该问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM