首页 > 其他分享 >System.ObjectDisposedException: Cannot access a disposed context instance

System.ObjectDisposedException: Cannot access a disposed context instance

时间:2023-06-30 18:22:39浏览次数:52  
标签:ObjectDisposedException EntityFrameworkCore created System disposed instance con

@@abp console project System.ObjectDisposedException: Cannot access a disposed context instance. A common cause of this error is disposing a context instance 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 instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.

System.ObjectDisposedException: Cannot access a disposed context instance #1753


User avatar
1
Mohammad created 2 years ago  

Hello

I am getting this error when I try to use a EF Core Repository which is resolved using ServiceProvider in CustomTenantResolver.

System.ObjectDisposedException: Cannot access a disposed context instance. A common cause of this error is disposing a context instance 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 instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.

Thanks

Check the docs before asking a question: https://docs.abp.io/en/commercial/latest/
Check the samples, to see the basic tasks: https://docs.abp.io/en/commercial/latest/samples/index
The exact solution to your question may have been answered before, please use the search on the homepage.

If you're creating a bug/problem report, please include followings:

  • ABP Framework version: v4.3.2

  • UI type: Angular

  • DB provider: EF Core

  • Tiered (MVC) or Identity Server Separated (Angular): yes

  • Exception message and stack trace:

  • Steps to reproduce the issue:"

 
8 Answer(s)
  • User Avatar
    0
    EngincanV created 2 years ago Support Team

    Hi @Mohammad, can you share where you used the repository (for example, your application service method)?

     
  • User Avatar
    0
    Mohammad created 2 years ago  

    Hi

    I am using it in Custom Tenant Resolver.

     public class AccessTokenTenantResolver : HttpTenantResolveContributorBase
        {
            public override string Name => "AccessToken";
    
    
    
            protected override async Task GetTenantIdOrNameFromHttpContextOrNullAsync(ITenantResolveContext context, HttpContext httpContext)
            {
               
    
                IClientCredentialRepository clientCredentialRepository = context.ServiceProvider.GetRequiredService();
    
                string accessCode = httpContext.Request.Headers["Authorization"];
    
                if (!string.IsNullOrEmpty(accessCode))
                {
                    var token = accessCode.Split(" ")[1];
                    var tokenHandler = new JwtSecurityTokenHandler();
                    var tokens = tokenHandler.ReadJwtToken(token);
                    var client_id = tokens.Claims.FirstOrDefault(x => x.Type == "client_id").Value;
                    var scopes = tokens.Claims.FirstOrDefault(x => x.Type == "scope").Value;
    
                    if (scopes.Contains("Scope"))
                    {
                        var client = await clientCredentialRepository.SingleOrDefaultAsync(x => x.ClientId == client_id);
    
                        if (client == null)
                            return await Task.FromResult(null);
    
                       
                        return await Task.FromResult(client.TenantId.Value.ToString());
                    }
                }
    
                return await Task.FromResult("37fb7b60-0ba6-8109-70b1-a049e5f25575");
            }
        }
    
     
  • User Avatar
    0
    EngincanV created 2 years ago Support Team

    Can you add the [UnitOfWork] attribute to above of your method and try it again?

     
  • User Avatar
    0
    Mohammad created 2 years ago  

    I am getting the same error even after adding [UnitOfWork]

    2021-08-23 16:01:08.732 +03:00 [WRN] System.ObjectDisposedException: Cannot access a disposed context instance. A common cause of this error is disposing a context instance 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 instance, or wrapping it 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: 'ClientManagementDbContext'.
       at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
       at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
       at Microsoft.EntityFrameworkCore.DbContext.get_ChangeTracker()
       at Microsoft.EntityFrameworkCore.Query.CompiledQueryCacheKeyGenerator.GenerateCacheKeyCore(Expression query, Boolean async)
       at Microsoft.EntityFrameworkCore.Query.RelationalCompiledQueryCacheKeyGenerator.GenerateCacheKeyCore(Expression query, Boolean async)
       at Npgsql.EntityFrameworkCore.PostgreSQL.Query.Internal.NpgsqlCompiledQueryCacheKeyGenerator.GenerateCacheKey(Expression query, Boolean async)
       at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken)
       at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)
       at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, Expression expression, CancellationToken cancellationToken)
       at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, LambdaExpression expression, CancellationToken cancellationToken)
       at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.SingleOrDefaultAsync[TSource](IQueryable`1 source, Expression`1 predicate, CancellationToken cancellationToken)
       at Zenithr.Tenant.Shared.AccessTokenTenantResolver.GetTenantIdOrNameFromHttpContextOrNullAsync(ITenantResolveContext context, HttpContext httpContext) in C:\websites\ZENITHR3.0\Zenithr.Shared.Tenant\AccessTokenTenantResolver.cs:line 43
       at Volo.Abp.AspNetCore.MultiTenancy.HttpTenantResolveContributorBase.ResolveFromHttpContextAsync(ITenantResolveContext context, HttpContext httpContext)
       at Volo.Abp.AspNetCore.MultiTenancy.HttpTenantResolveContributorBase.ResolveAsync(ITenantResolveContext context)
    
     
  • User Avatar
    1
    maliming created 2 years ago Support Team

    hi Mohammad

    Can you try this:

    using (var uow = _unitOfWorkManager.Begin()
    {
        var client = await clientCredentialRepository.SingleOrDefaultAsync(x => x.ClientId == client_id);
        await uow.CompleteAsync();
    }
    
    
     
  • User Avatar
    1
    Mohammad created 2 years ago  

    the using statement worked.

    Why do I need to do the using for Unitofwork for the repository to work? can you explain? Is this a workaround or an actual solution?

     
  • User Avatar
    1
    maliming created 2 years ago Support Team

    hi

    The GetTenantIdOrNameFromHttpContextOrNullAsync method not in a uow because the middleware order.

    And the AccessTokenTenantResolver is created by new instead of DI, so the [UnitOfWork] won't work

    image.png

    In this case you need to create uow manually.

    image.png

     
  • User Avatar
    0
    Mohammad created 2 years ago  

    Thanks for the Explaination and refund.

     

 

标签:ObjectDisposedException,EntityFrameworkCore,created,System,disposed,instance,con
From: https://www.cnblogs.com/wl-blog/p/17517576.html

相关文章

  • Students-system开发步骤
    项目初始化新建文件夹,命名为students-system,注意这里的命名不得为中文或其他特殊字符npminit-y安装包npmijqueryexpressexpress-art-template新建文件夹新建public,views文件夹,public下新建img,js,css文件夹,目录如下:student-systemnode_modulespublicim......
  • Students-system开发步骤
    #Students-system开发步骤##项目初始化新建文件夹,命名为`students-system`,注意这里的命名不得为中文或其他特殊字符```shellnpminit-y```##安装包```shellnpmijqueryexpressexpress-art-template```##新建文件夹新建public,views文件夹,public下新建img,js,css文件夹,目录如......
  • mass mess Monolithic system 单体系统的问题
    1.单体系统太大了最首要的一个原因就是应用系统太大。而由于应用系统的过于庞大,如果仅是单体系统的话,就引发了各种各样的问题,体现在以下三个方面:1.1.系统本身业务复杂,模块众多系统随着时间的发展,业务需求越来越多。而为了满足这些需求,就导致整个系统的模块越来越多。而系统模......
  • ln -s /dev/null /root/etc/systemd/system/snapd.service
    disablesnapdduringdell-recoveryrunIt'snotneeded,thisspeedsuptherebootbetweenstagesandpreventsOOMonlowmemoryconfigsforinstaller. 这段代码用于在安装过程中禁用snapd服务,以避免在资源较小的配置上出现OOM(OutofMemory)问题。以下是代码的解......
  • Android system & system_ext & product等分区中的build.prop文件是怎么生成的?
    Androidsystem&system_ext&product等分区中的build.prop文件是怎么生成的? #http://aospxref.com/android-13.0.0_r3/xref/build/make/core/sysprop.mk #http://aospxref.com/android-13.0.0_r3/xref/build/make/tools/buildinfo.sh buildinfo.sh脚本内容:#!/bin......
  • 关于CIFS-Common Internet File System-通用Internet文件系统
    服务器消息块(SMB)协议是一种网络文件共享协议,在MicrosoftWindows中实现的称为MicrosoftSMB协议。定义特定版本的协议的消息数据包集称为方言。通用Internet文件系统(CIFS)协议是SMB的方言。VMS、Unix的多个版本和其他操作系统上也提供SMB和CIFS。 CIFS是......
  • C# 避免使用System.Environment.CurrentDirectory
    我有一个程序A(exe)是通过计划任务程序启动,发现通过System.Environment.CurrentDirectory获取的路径不是程序A的运行目录,而是C:\Windows\System32DirectoryInfotopDir=Directory.GetParent(System.Environment.CurrentDirectory);是因为System.Environment.CurrentDirectory......
  • Online Temporal Calibration for Monocular Visual-Inertial Systems
    摘要:准确的状态估计是各种智能应用的基本模块,例如机器人导航、自动驾驶、虚拟和增强现实。近年来,视觉和惯性融合是一种流行的技术,用于6自由度状态估计。不同传感器测量记录的时间点对于系统的鲁棒性和准确性非常重要。实际上,每个传感器的时间戳通常会受到触发和传输延迟的影响,导......
  • HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Secureboot
    regaddHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Secureboot/vAvailableUpdates/tREG_DWORD/d0x10/f命令是用于在注册表中添加一个名为"AvailableUpdates"的DWORD值,并将其设置为十六进制值"0x10"。此操作需要管理员权限才能执行。这个命令的作用是向......
  • system halt during installation with NV graphics card.
    Icheck,itseemsitisstuckat"GETubiquity/install_oem".Canyoucheck/var/cache/debconf/config.dat,iftheubiquity/install_oemvalueisTrue.itisin/usr/share/ubiquity/simple-pluginsscript,itsetthedbtotrueandgetitdirectlyin......