gpt4 book ai didi

c# - 使用依赖注入(inject)时如何修复 'A second operation started on this context before a previous operation completed...'?

转载 作者:行者123 更新时间:2023-11-30 23:08:38 24 4
gpt4 key购买 nike

从数据库中读取数据时出现此错误:

A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.

我有以下 ApplicationContext.cs:

public class ApplicationContext : Microsoft.EntityFrameworkCore.DbContext
{
public ApplicationContext(DbContextOptions<ApplicationContext> options)
: base(options)
{ }

public DbSet<MyClass> MyClasses{ get; set; }
}

下面的ApplicationContextFactory.cs

public class ApplicationContextFactory : IDesignTimeDbContextFactory<ApplicationContext>
{
public ApplicationContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<ApplicationContext>();
var connection = "myConnectionString";

builder.UseSqlServer(connection);

return new ApplicationContext(builder.Options);
}
}

以下 ServiceLoader.cs(我在其中声明 DI):

public static class ServiceLoader
{
public static void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IRepository, Repository>();

var connection = "myConnectionString";
services.AddDbContext<ApplicationContext>(options => options.UseSqlServer(connection));
}
}

最后是抛出异常的以下存储库:

public class Repository : IRepository
{
private ApplicationContext _db;

public Repository (ApplicationContext db)
{
_db = db;
}

public List<MyClass> Get()
{
_db.MyClasses.ToList();
}
}

我也曾尝试将 Repository 声明为 Transient 而不是 Singleton,但抛出了类似的错误

'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.'

知道如何解决这个问题吗?谢谢!

最佳答案

就我而言,我发现以下信息很有用:

https://learn.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext

并在启动时使用重载的 AddDbContext 方法将我的 Db 上下文的生命周期范围更改为 transient :

services.AddDbContext<MyAppDbContext>(options => {
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection"));
}, ServiceLifetime.Transient);

关于c# - 使用依赖注入(inject)时如何修复 'A second operation started on this context before a previous operation completed...'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46395150/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com