C# EF6 make multiple async calls to one context us

2019-08-02 06:46发布

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条回答
等我变得足够好
2楼-- · 2019-08-02 07:28

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

container.RegisterType<DbContext>(new PerRequestLifetimeManager());
container.RegisterType<ISupplierRepository, SupplierRepository>();
container.RegisterType<IContactRepository, ContactRepository>();
查看更多
登录 后发表回答