繁体   English   中英

错误:无法访问已处理的对象。 此错误的一个常见原因是处理从依赖注入解决的上下文

[英]Error: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection

我正在 dotnet core 2.2 上开发一个应用程序

自从两天以来,我一直在受这个如此著名的问题的困扰。 我一次又一次地修改了以下链接,但这些似乎不起作用:

但似乎没有什么能解决问题。

public class UserAccountController : BaseController
{
    private readonly UserAccountBL _userAccountBL;

    public UserAccountController(IConfiguration configuration,
                      ILogger<UserAccountBL> logger, ApplicationDbContext db, UserManager<AppUser> accountManager)
    {
        _userAccountBL = new UserAccountBL(configuration,logger,db, accountManager);
    }

    [HttpPost("addnewUser")]
    public async Task<IActionResult> AddNewUser(UserVM user)
    {
        try
        {
            var result = _userAccountBL.AddUser(user);
            return Ok(result);
        }
        catch(NotFoundException e)
        {
            return Ok(new NotFoundError(e.Message));
        }
    }
}

public class DeliveryManagerAccountBL
{
    private readonly IConfiguration _configuration;
    private readonly ILogger<UserAccountBL> _logger;
    private readonly ApplicationDbContext _context;
    private readonly UserManager<AppUser>_accountManager;

    public UserAccountBL(IConfiguration configuration,
                      ILogger<UserAccountBL> logger, ApplicationDbContext db, UserManager<AppUser> accountManager)
    {
        _configuration  = configuration;
        _logger         = logger;
        _context        = db;
        _accountManager = accountManager;
    }

    public async Task<bool> AddUser( AddRiderVM user)
    {
        if (CheckEmailExist(model.EmailAddress))
        {
            throw new InvalidOperationException("Email already exist");
        }
        if (CheckPhoneExist(model.MobileNumber))
        {
            throw new InvalidOperationException("Mobile number already exist");
        }

        var newUserID = Guid.NewGuid().ToString();
        var user = new AspNetUser
        {
            UserName = user.EmailAddress,
            Email = user.EmailAddress,
            Id = newUserID,
            PhoneNumber = user.MobileNumber
        };

        var password = "Dumy123@";

        try
        {
            List<string> roles = new List<string>();

            **var result = await _accountManager.CreateAsync(user, password);**

            if (result.Succeeded)
            {
              //Something will happen
            }
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        return false;
    }
}

以下异常发生在 ** 行。

无法访问已处置的对象。 此错误的一个常见原因是处理从依赖注入解析的上下文,然后尝试在应用程序的其他地方使用相同的上下文实例。 如果您在上下文上调用 Dispose() 或将上下文包装在 using 语句中,则可能会发生这种情况。 如果你使用依赖注入,你应该让依赖注入容器来处理上下文实例。 对象名称:'ApplicationDbContext'。

以下是我的 Program.cs 文件

public class Program
{
    public static void Main(string[] args)
    {
       var host = CreateWebHostBuilder(args).Build();

        //seed database
        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;

            try
            {
                var databaseInitializer = services.GetRequiredService<IDatabaseInitializer>();
                databaseInitializer.SeedAsync().Wait();
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogCritical(LoggingEvents.INIT_DATABASE, ex, LoggingEvents.INIT_DATABASE.Name);

                throw new Exception(LoggingEvents.INIT_DATABASE.Name, ex);
            }
        }
        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

编辑:堆栈跟踪:

at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.<SaveChangesAsync>d__53.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.<CreateAsync>d__22.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Identity.UserManager`1.<CreateAsync>d__74.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Identity.UserManager`1.<CreateAsync>d__79.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at StilaarApi.Core.AccountManager.<CreateUserAsync>d__10.MoveNext() in D:\project stilaar\pinchapi\Core\AccountManager.cs:line 106

我在调用函数 await _userAccountBL.AddUser(user); 时缺少 await 关键字;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM