当我试图从数据库异步获取一些数据时,我遇到下一个错误:
Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. Object name: AsyncDisposer
在这种方法中:
private async List<SomeData> TestData()
{
var testData = await _cache.GetAsync<List<SomeData>("TestData");
if (testData == null)
{
var testData = await MyDbContext.SomeDatas.ToListAsync();
await _cache.SetAsync<List<SomeData>("TestData", testData);
}
return testData;
}
在ToListAsync()
处出现异常,但没有异步方法,一切正常。
DbContext:
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options)
: base(options)
{
}
public virtual DbSet<SomeData> SomeDatas { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new SomeDataConfiguration());
base.OnModelCreating(modelBuilder);
}
}
public class SomeDataConfiguration : IEntityTypeConfiguration<SomeData>
{
public void Configure(EntityTypeBuilder<SomeData> builder)
{
builder.ToTable("SomeDatas");
builder.Property(e => e.Value)
.IsRequired();
}
}
答案 0 :(得分:0)
using(DbContext db = new DbContext()) {
data = await db.SomeData.ToListAsync();
}
使用将负责处置资源。