简体   繁体   English

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

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

I am developing an application on dotnet core 2.2我正在 dotnet core 2.2 上开发一个应用程序

since two days I have been suffering from this so famus issue.自从两天以来,我一直在受这个如此著名的问题的困扰。 I have revisted following links again and again but these not seems to work:我一次又一次地修改了以下链接,但这些似乎不起作用:

but nothing seems to resolve the problem.但似乎没有什么能解决问题。

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;
    }
}

following exception occur at the ** line.以下异常发生在 ** 行。

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.如果您在上下文上调用 Dispose() 或将上下文包装在 using 语句中,则可能会发生这种情况。 If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.如果你使用依赖注入,你应该让依赖注入容器来处理上下文实例。 Object name: 'ApplicationDbContext'.对象名称:'ApplicationDbContext'。

Following is my Program.cs file以下是我的 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>();
}

Edit : Stack Trace:编辑:堆栈跟踪:

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.

相关问题 &#39;无法访问已处理的对象。 此错误的一个常见原因是处理从依赖注入解决的上下文 - 'Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection 无法访问已处置的 object。 此错误的常见原因是处理从依赖注入中解析的上下文 - Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection Asp.net 内核:无法访问已处置的 object。 此错误的常见原因是处理从依赖注入中解析的上下文 - Asp.net core: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection .Net core/EF:无法访问已处置的 object。 此错误的常见原因是处理上下文 - .Net core/EF : cannot access a disposed object. A common cause of this error is disposing a context 无法访问已处理的对象。此错误的原因 - 与依赖注入相关的 Asp.net Core 异常 - Cannot access a disposed object.cause of this error - Asp.net Core Exception related to Dependency Injection c#XNA无法访问已处置的对象。 对象名称:“ Texture2D”。 但是我没有处理它 - c# XNA Cannot access a disposed object. Object name: 'Texture2D'. But im not disposing it 无法访问已处置的 object。 Object 名称:AspNet Core/EF Core 项目中出现“IServiceProvider”错误 - Cannot access a disposed object. Object name: 'IServiceProvider' error in AspNet Core/EF Core project Azure function 启动时出错:无法访问已处置的 object。Object 名称:'IServiceProvider' - Azure function error on startup: Cannot access a disposed object. Object name: 'IServiceProvider' 尝试运行SpecFlow NUnit测试时出错:“无法访问已处置的对象。 对象名称:“ GherkinLanguageService”” - Error when attempting to run SpecFlow NUnit test: “Cannot access a disposed object. Object name: 'GherkinLanguageService'” 无法访问已处置的对象错误 - Cannot access a disposed object error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM