How to resolve an EF Core issue where context is used during configuration?

2026-05-17 01:431阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计290个文字,预计阅读时间需要2分钟。

How to resolve an EF Core issue where context is used during configuration?

错误信息:尝试在配置过程中使用上下文。在此时,DbContext实例不能在OnConfiguring中使用,因为它仍在配置中。这可能会发生。

报错信息:

System.InvalidOperationException: An attempt was made to use the context while it is being configured. A DbContext instance cannot be used inside OnConfiguring since it is still being configured at this point. This can happen if a second operation is started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.

我在前台同时请求两个后台接口,然后发现经常会出现一个接口正常而另一个接口报错的问题。查询网上资料后,一个解决方法是把Startup文件里配置数据库的 context生命周期改为每次请求都实例化一下。我更改之后,刷新了几次页面发现这个改法可行。不过过了一会儿,我再次刷新页面时,发现原来那个问题又出现了,也就是说问题没有解决。

How to resolve an EF Core issue where context is used during configuration?

一次偶然间,我突然发现我的_context 定义的是静态类...我人傻了,改为非静态来之后,可以了。

本文共计290个文字,预计阅读时间需要2分钟。

How to resolve an EF Core issue where context is used during configuration?

错误信息:尝试在配置过程中使用上下文。在此时,DbContext实例不能在OnConfiguring中使用,因为它仍在配置中。这可能会发生。

报错信息:

System.InvalidOperationException: An attempt was made to use the context while it is being configured. A DbContext instance cannot be used inside OnConfiguring since it is still being configured at this point. This can happen if a second operation is started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.

我在前台同时请求两个后台接口,然后发现经常会出现一个接口正常而另一个接口报错的问题。查询网上资料后,一个解决方法是把Startup文件里配置数据库的 context生命周期改为每次请求都实例化一下。我更改之后,刷新了几次页面发现这个改法可行。不过过了一会儿,我再次刷新页面时,发现原来那个问题又出现了,也就是说问题没有解决。

How to resolve an EF Core issue where context is used during configuration?

一次偶然间,我突然发现我的_context 定义的是静态类...我人傻了,改为非静态来之后,可以了。