Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

Getting UserManager is disposed error in UserFriendsCache #5403


User avatar
0
altinero created

When changing users (via impersonation), I'm getting this error. I haven't changed any code related to Chat or Users.

ERROR 2018-07-20 08:50:23,484 [75 ] Mvc.ExceptionHandling.AbpExceptionFilter - Cannot access a disposed object. Object name: 'UserManagerProxy'. System.ObjectDisposedException: Cannot access a disposed object. Object name: 'UserManagerProxy'. at Microsoft.AspNetCore.Identity.UserManager1.ThrowIfDisposed() at Microsoft.AspNetCore.Identity.UserManager1.FindByIdAsync(String userId) at Castle.Proxies.Invocations.UserManager1_FindByIdAsync.InvokeMethodOnTarget() at Castle.DynamicProxy.AbstractInvocation.Proceed() at Castle.DynamicProxy.AbstractInvocation.Proceed() at Castle.Proxies.UserManagerProxy.FindByIdAsync(String userId) at Friendships.Cache.UserFriendsCache.<>c__DisplayClass15_0.<GetUserFriendsCacheItemInternal>b__5() in UserFriendsCache.cs:line 188 at System.Threading.Tasks.Task1.InnerInvoke() at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) --- End of stack trace from previous location where exception was thrown --- at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot) --- End of stack trace from previous location where exception was thrown --- at Nito.AsyncEx.Synchronous.TaskExtensions.WaitAndUnwrapException[TResult](Task1 task) at System.Threading.Tasks.ContinuationResultTaskFromResultTask2.InnerInvoke() at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) --- End of stack trace from previous location where exception was thrown --- at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot) --- End of stack trace from previous location where exception was thrown --- at Nito.AsyncEx.Synchronous.TaskExtensions.WaitAndUnwrapException[TResult](Task1 task) at Nito.AsyncEx.AsyncContext.Run[TResult](Func1 action) at Friendships.Cache.UserFriendsCache.GetUserFriendsCacheItemInternal(UserIdentifier userIdentifier) in UserFriendsCache.cs:line 188 at Castle.Proxies.Invocations.UserFriendsCache_GetUserFriendsCacheItemInternal.InvokeMethodOnTarget() at Castle.DynamicProxy.AbstractInvocation.Proceed() at Abp.Domain.Uow.UnitOfWorkInterceptor.PerformSyncUow(IInvocation invocation, UnitOfWorkOptions options) in D:\Github\aspnetboilerplate\src\Abp\Domain\Uow\UnitOfWorkInterceptor.cs:line 68 at Castle.DynamicProxy.AbstractInvocation.Proceed() at Castle.Proxies.UserFriendsCacheProxy.GetUserFriendsCacheItemInternal(UserIdentifier userIdentifier) at Friendships.Cache.UserFriendsCache.<>c__DisplayClass8_0.<GetCacheItem>b__0(String f) in UserFriendsCache.cs:line 46 at Abp.Runtime.Caching.CacheExtensions.<>c__DisplayClass3_02.<Get>b__0(String k) in D:\Github\aspnetboilerplate\src\Abp\Runtime\Caching\CacheExtensions.cs:line 28 at Abp.Runtime.Caching.CacheBase.Get(String key, Func2 factory) in D:\Github\aspnetboilerplate\src\Abp\Runtime\Caching\CacheBase.cs:line 66 at Abp.Runtime.Caching.CacheExtensions.Get[TKey,TValue](ICache cache, TKey key, Func`2 factory) in D:\Github\aspnetboilerplate\src\Abp\Runtime\Caching\CacheExtensions.cs:line 28 at Friendships.Cache.UserFriendsCache.GetCacheItem(UserIdentifier userIdentifier) in UserFriendsCache.cs:line 44 at Castle.Proxies.Invocations.UserFriendsCache_GetCacheItem.InvokeMethodOnTarget() at Castle.DynamicProxy.AbstractInvocation.Proceed() at Abp.Domain.Uow.UnitOfWorkInterceptor.PerformSyncUow(IInvocation invocation, UnitOfWorkOptions options) in D:\Github\aspnetboilerplate\src\Abp\Domain\Uow\UnitOfWorkInterceptor.cs:line 68 at Castle.DynamicProxy.AbstractInvocation.Proceed() at Castle.Proxies.UserFriendsCacheProxy.GetCacheItem(UserIdentifier userIdentifier) at Chat.ChatAppService.GetUserChatFriendsWithSettings() in ChatAppService.cs:line 47 at lambda_method(Closure , Object , Object[] ) at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextExceptionFilterAsync() INFO 2018-07-20 08:50:23,486 [75 ] .Mvc.Infrastructure.ObjectResultExecutor - Executing ObjectResult, writing value of type 'Abp.Web.Models.AjaxResponse'. INFO 2018-07-20 08:50:23,486 [75 ] ore.Mvc.Internal.ControllerActionInvoker - Executed action Chat.ChatAppService.GetUserChatFriendsWithSettings in 145.0636ms INFO 2018-07-20 08:50:23,486 [75 ] soft.AspNetCore.Hosting.Internal.WebHost - Request finished in 154.1466ms 500 application/json; charset=utf-8 INFO 2018-07-20 08:52:08,665 [chdog] Hangfire.Server.ServerWatchdog - 1 servers were removed due to timeout

Boilerplate code where this is happening:

[UnitOfWork]
        protected virtual UserWithFriendsCacheItem GetUserFriendsCacheItemInternal(UserIdentifier userIdentifier)
        {
            var tenancyName = userIdentifier.TenantId.HasValue
                ? _tenantCache.GetOrNull(userIdentifier.TenantId.Value)?.TenancyName
                : null;

            using (_unitOfWorkManager.Current.SetTenantId(userIdentifier.TenantId))
            {
                var friendCacheItems =
                    (from friendship in _friendshipRepository.GetAll()
                     join chatMessage in _chatMessageRepository.GetAll() on
                     new { UserId = userIdentifier.UserId, TenantId = userIdentifier.TenantId, TargetUserId = friendship.FriendUserId, TargetTenantId = friendship.FriendTenantId, ChatSide = ChatSide.Receiver } equals
                     new { UserId = chatMessage.UserId, TenantId = chatMessage.TenantId, TargetUserId = chatMessage.TargetUserId, TargetTenantId = chatMessage.TargetTenantId, ChatSide = chatMessage.Side } into chatMessageJoined
                     where friendship.UserId == userIdentifier.UserId
                     select new FriendCacheItem
                     {
                         FriendUserId = friendship.FriendUserId,
                         FriendTenantId = friendship.FriendTenantId,
                         State = friendship.State,
                         FriendUserName = friendship.FriendUserName,
                         FriendTenancyName = friendship.FriendTenancyName,
                         FriendProfilePictureId = friendship.FriendProfilePictureId,
                         UnreadMessageCount = chatMessageJoined.Count(cm => cm.ReadState == ChatMessageReadState.Unread)
                     }).ToList();

//********* this is the _userManager that throws the exception   ***************************//
                var user = AsyncHelper.RunSync(() => _userManager.FindByIdAsync(userIdentifier.UserId.ToString())); 

                return new UserWithFriendsCacheItem
                {
                    TenantId = userIdentifier.TenantId,
                    UserId = userIdentifier.UserId,
                    TenancyName = tenancyName,
                    UserName = user.UserName,
                    ProfilePictureId = user.ProfilePictureId,
                    Friends = friendCacheItems
                };
            }
        }

Anyone seen something like this?


9 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team

    Please share all the code of UserFriendsCache.cs.

  • User Avatar
    0
    bryan created

    I can confirm this is happening too, the code is exactly the same as in release 5.6.1

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi All,

    Could you write steps to reproduce this problem with a fresh download ? We have tried but couldn't reproduce it on our side.

    Thanks.

  • User Avatar
    0
    OutdoorEd created

    I had this same issue while developing locally. I spent 8 hours on Saturday coding, building and testing and 6 hours on Sunday - absolutely no problems. Then after one build it threw this same error. I had never touched any code related to the friend service. I ended up rebooting my computer (which showed a memory error on shutdown). When I restarted and built my solution again, the problem was gone. Three more hours of building and testing - no problem. Memory leak?

  • User Avatar
    0
    ismcagdas created
    Support Team

    Could you create an issue here <a class="postlink" href="https://github.com/aspnetzero/aspnet-zero-core/issues/new">https://github.com/aspnetzero/aspnet-ze ... issues/new</a> and let us test it deeply.

  • User Avatar
    0
    ISTeam created

    Even after two years, surprisingly same thing happened like above comment of @outdoored.

    I was spending more than two days to resolve the problem of ObjectDisposedException to access repository in my own separate console applicaiton to be used as a task scheduler job independently just to import data. I first used the exact same code of 'X.Migrator' application and just added my code in the 'MultiTenantMigrateExecuter.Run()' method to access some other reposiotry of the same database. But unfortunately I was getting same error. Even [UnitOfWork] did not work for me.

    And as last hope, I restarted my machine and suddenly after restart it is working with [UnitOfWork]! with Tenant repository onlu which is defined by Abp. But not for any other entities created by us.

  • User Avatar
    0
    BigCDogCrew created

    I am seeing the same problem in AspNetZero v7.2.0 MVC jQuery.
    I opened the following issue as requested above. https://github.com/aspnetzero/aspnet-zero-core/issues/3569 More detials are provided there.

  • User Avatar
    0
    BigCDogCrew created

    A working solution has been documented at the GitHub link above.

  • User Avatar
    0
    rcasaca created

    Hi all, Sorry to post on a closed topic but i have a similar problem.

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

    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: 'CustomerHubDbContext'. at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed() at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies() at Microsoft.EntityFrameworkCore.DbContext.get_Model() at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.get_EntityType() at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.get_EntityQueryable() at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.System.Collections.Generic.IEnumerable<TEntity>.GetEnumerator() at CustomerHub.Jobs.SyncBusinessPartners.Execute(Int32 x) in C:_GIT\SyncBusinessPartners.cs:line 42

    Below the code of SyncBusinessPartners Job (highlighted the row in error - line42)

    public class SyncBusinessPartners : BackgroundJob<int>, ITransientDependency
    {
    	private readonly TenantManager _tenantManager;
    	private readonly IAbpSession _abpSession;
    	private readonly UserManager _userManager;
    	private readonly ILogger<SyncBusinessPartners> _logger;
    
    	public SyncBusinessPartners(
    		TenantManager tenantManager,
    		IAbpSession abpSession,
    		UserManager userManager,
    		ILogger<SyncBusinessPartners> logger
    	)
    	{
    		_tenantManager = tenantManager;
    		_abpSession = abpSession;
    		_userManager = userManager;
    		_logger = logger;
    		LocalizationSourceName = CustomerHubConsts.LocalizationSourceName;
    	}
    
    	public override void Execute(int x)
    	{
    		_logger.LogInformation(L("JobExecutionStarted", args: $"{nameof(SyncBusinessPartners)}"));
    
    		**foreach (var t in _tenantManager.Tenants)**
    		{
    			var admin = _userManager.FindByNameAsync("admin").Result;
    		}
    
    		_logger.LogInformation(L("JobExecutionFinished", args: nameof(DocumentDto)));
    	}
    }