c# - DBContext : Getting disposed without calling Dispose(). 未使用 using 语句

标签 c# asp.net-core dependency-injection entity-framework-core

我正尝试在我的 dbcontext 上调用一些查询。我已将数据保存在数据库中,现在正尝试在线程中再次提取数据以进行进一步处理,但无法这样做。 dbcontext 按配置出现。

我已经尝试将 dbcontext 的服务生命周期从默认范围修改为单例和 transient ,并将分类调用 dbcontext 的生命周期更改为 transient 。

服务添加:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<PearlIDPContext>(options => options.UseMySQL(Configuration.GetConnectionString("IDPDatabase")), optionsLifetime: ServiceLifetime.Transient);
    services.AddScoped<IScanDataRepository, ScanDataRepository>();
    services.AddScoped<IOperationsRepository, OperationHistoryRepository>();
    services.AddScoped<IExtractedDataRepository, ExtractedDataRepository>();
    services.AddScoped<IExtractedColorsRepository, ExtractedColorsRepository>();
    services.AddScoped<IRejectionsRepository, RejectionsRepository>();
    services.AddScoped<IStartProcess, StartProcess>();
}

数据库修改类:

public class ScanDataRepository : IScanDataRepository
{
    private readonly PearlIDPContext context;

    public ScanDataRepository(PearlIDPContext context)
    {
        this.context = context;
    }
    public async Task<ScanData> AddAsync(ScanData scan) [modified]
    {
        context.ScanData.Add(scan);
        await context.SaveChangesAsync();
        return scan;
    }
    public ScanData GetScanData(string pearlId)
    {
       return context.ScanData.FirstOrDefault(o => o.PearlId == pearlId);
    }
}

调用修改类:

scanDataRepository.AddAsync(scanData);

try
{
    Logger.WriteToLogFile("Fetching Scan details from database for pearlID : " + pearlId, pearlId);

    scanData = scanDataRepository.GetScanData(pearlId); // this is line 39
    int id = scanData.ScanId;
    Logger.WriteToLogFile("Fetching Scan details from database successful for pearlID : " + pearlId + ". DB table id : " + id, pearlId);
}
catch (Exception ex)
{
    Logger.WriteToErrorFile("Error getting data from databse. Pearl ID : " + pearlId + ". Error : " + ex.ToString());
}

Error getting data from database. Pearl ID : PI09889. Error : System.ObjectDisposedException: 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: 'PearlIDPContext'. at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed() at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Internal.IDbContextDependencies.get_StateManager() at Microsoft.EntityFrameworkCore.Query.QueryContextDependencies.get_StateManager() at Microsoft.EntityFrameworkCore.Query.QueryContext.get_StateManager() at Microsoft.EntityFrameworkCore.Query.QueryContext.BeginTrackingQuery() at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider._TrackEntities[TOut,TIn](IEnumerable`1 results, QueryContext queryContext, IList`1 entityTrackingInfos, IList`1 entityAccessors)+MoveNext() at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext() at System.Linq.Enumerable.TryGetFirst[TSource](IEnumerable`1 source, Boolean& found) at System.Linq.Enumerable.First[TSource](IEnumerable`1 source) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass15_1`1.b__0(QueryContext qc) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query) at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression) at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source, Expression`1 predicate) at MyndIT.Models.ScanDataRepository.GetScanData(String pearlId) in D:\Projects\Github\PearlIDP\MyndIT\Models\ScanDataRepository.cs:line 33 at MyndIT.StartProcess.ProcessStart(String pearlId) in D:\Projects\Github\PearlIDP\MyndIT\StartProcess.cs:line 39

最佳答案

您需要将 DbContext 保持为 transient 。我以前遇到过很多次这个问题。发生的事情是该方法正在完成并在您的线程完成之前处理您的上下文。如果您使用线程来阻止 UI 锁定,那么您应该使用 await 关键字(实际上您无论如何都应该使用 await)。

关于c# - DBContext : Getting disposed without calling Dispose(). 未使用 using 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58797949/

相关文章:

c# - 在后台/异步任务中插入数据最好的方法是什么?

c# - 如何在 WebBrowser 控件中获取呈现的 html(由 Javascript 处理)?

c# - Redis StackExchange 删除键

c# - 有没有办法为每种转发类型设置不同的生命周期?

java - Bean 被初始化但注入(inject)抛出 npe

c# - 将文本复制到剪贴板错误 CS1503 参数 2 : cannot convert from 'string' to 'System.Windows.Forms.TextDataFormat'

c# - 是否有更有效的方法来编写使用 DateTime 值的 IF 语句?

visual-studio - 使用 Visual Studio 2015 进行调试时无法在 View 中编辑 C# 代码

c# - .NET Core iHostedService 关闭 IIS

java - 基于构造函数的依赖注入(inject)如何影响不可变性?