0

In my method below which is written using c# in asp.net core, I am getting error when executing any of the below update statements. What is the issue with using await SaveContextAsync(); I have noticed I dont get error when only using SaveContext();

The error that I am getting is as follows

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

I am not sure why I am getting this error.

 public async Task<IdentityResult> ApproveUserChangeRequest(UserChangeRequest userChangeRequest, string approvedByAuthUserName, string authApplicationName)
    {
        var userChangeRequestRepository = UserChangeRequestRepository.GetAllAsList();
        var userChangeRequestApprovalRepository = UserChangeRequestApprovalRepository.GetAllAsList();
        var appSettingRepository = AppSettingRepository.GetAllAsList();
        var clientCompanyContactRepository = ClientCompanyContactRepository.GetAllAsList();
        var applicationUserRepo = ApplicationUserRepo.GetAllAsList();
        int approvedByAuthUserID = GetApprovedByUserId(authApplicationName, approvedByAuthUserName);

        // Check if UserChangeRequest is still Pending
        bool isUserChangeRequestPending = userChangeRequestRepository.Any(x => x.Id == userChangeRequest.Id && x.ChangeStatus == "Pending");

        if (isUserChangeRequestPending && approvedByAuthUserID > 0)
        {
            // Inserting record in the UserChangeRequestApproval table
            InsertUserChangeRequestApproval(userChangeRequest);
            await SaveContextAsync();

            using (var userTransaction = Context.Database.BeginTransaction())
            {
                using (var securityTransaction = _securityContext.Database.BeginTransaction())
                {
                    try
                    {
                        //Get the Number of approval required for Internal and External Users
                        int? internalApprovalsRequired = GetApprovals("InternalUserChangeRequestApprovalsRequired", appSettingRepository);
                        int? externalApprovalsRequired = GetApprovals("ExternalUserChangeRequestApprovalsRequired", appSettingRepository);

                        //Get the name of the application the auth user belongs to
                        var authUserApplicationName = GetApplicationName(userChangeRequest.AuthUserId);

                        //Get the Number of approvals for the request
                        var numberOfAprovals = userChangeRequestApprovalRepository.Where(x => x.UserChangeRequestId == userChangeRequest.Id).Count();

                        //If the number of approvals is equal or greater than the Approvals required then Update AppUser or Contact details
                        if ((authUserApplicationName == "ArgentexTrader" && numberOfAprovals >= internalApprovalsRequired) || (authUserApplicationName == "ArgentexClient" && numberOfAprovals >= externalApprovalsRequired))
                        {
                            //Updating the clientcontact table
                            UpdateClientContact(userChangeRequest, clientCompanyContactRepository);


                            //Updating the auth user table
                            UpdateAuthUser(userChangeRequest);


                            //Updating the IdentityDB user table
                            UpdateIdentityDBUser(userChangeRequest, applicationUserRepo);

                            //Updating the UserChangeRequest table
                            userChangeRequest.ChangeStatus = "Approved";
                            UserChangeRequestRepository.Update(userChangeRequest);

                            await SaveContextAsync();
                            userTransaction.Commit();
                            securityTransaction.Commit();
                            return IdentityResult.Success;
                        }

                    }
                    catch (Exception ex)
                    {
                        userTransaction.Rollback();
                        securityTransaction.Rollback();
                        _logger.Error(ex);
                        return IdentityResult.Failed(new IdentityError { Description = ex.Message });
                    }
                }
            }
        }
        return null;
    }
Tom
  • 8,175
  • 41
  • 136
  • 267
  • Are all those repositories static? And what is the code of `SaveContextAsync`? Are you or are you not using DI? – ZorgoZ Nov 05 '19 at 17:05
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Trevor Nov 05 '19 at 17:09
  • My guess is you're failing to `await` something somewhere, and your code exits the `using` block before it has a chance to run. – John Wu Nov 06 '19 at 01:41

1 Answers1

0

The error says that a resolved context is been trying to made Disposable.

For More Information: Using Statements in C#

using statement is a scope only process, so this error means that your program tries to use the same instances of "context" in somewhere else, which it cant use it, because as I mentioned it is a "scope only" process.

In your example:

using (var userTransaction = Context.Database.BeginTransaction())
{
   using (var securityTransaction = _securityContext.Database.BeginTransaction())
   {
   }
}

You can make it simple and dont use a using scope or you can be sure that, the context is just used in those using scopes.

Burak
  • 467
  • 4
  • 16