DbContext上的ObjectDisposedException

问题描述 投票:0回答:1

使用从另一个服务注入到服务中的DbContext时出现以下错误:

ObjectDisposedException: Cannot access a disposed object.

我的DbContext的生存期是Scoped,而我的服务的生存期是Transient,但是将其更改为Singleton(我们不希望)而不解决这个问题。

有趣的是,错误似乎是随机发生的。有时没有错误,一切正常。

关于此错误,当我的Angular应用开始向后端触发请求时,我(也是随机地)在启动后立即得到了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."

我的代码:

public class MyService1 {

    private static IMyService2 _myService2;

    public MyService1(IMyService2 myService2){
        _myService2 = myService2;
    }

    public async Task DoSomethingWithMyService2() {
        await _myService2.DoSomething(new MyEntity());
    }
}
public class MyService2 : IMyService2 {

    private MyDbContext _dbContext;

    public MyService2(MyDbContext myDbContext) {
        _dbContext = myDbContext;
    }

    public async Task DoSomething(MyEntity myEntity) {
        await _dbContext.MySet.AddAsync(myEntity); // <-- ObjectDisposedException
        await _dbContext.SaveChangesAsync();
    }
}
asp.net-core entity-framework-core dbcontext asp.net-core-2.1
1个回答
0
投票

回答我自己的问题:罪魁祸首是在将MyService2注入static后将其存储在MyService1字段中。

由于DbContext的生存期为Scoped,将在对服务的初始请求后将其丢弃。但是,该服务将在引用整个应用程序的DbContext的整个生存期内继续运行。

((对于应用程序的生命周期,我并不完全确定,因为MyService1本身也是Transient。也许其他人可以解释它的工作原理。)

© www.soinside.com 2019 - 2024. All rights reserved.