c# - 无法访问已处置的对象。对象名称 : 'IServiceProvider' error in AspNet Core/EF Core project

标签 c# asp.net-core dependency-injection mediatr

我正在使用 Entity Framework Core 编写一个 ASP.NET Core 应用程序。我也在使用 MediatR。

当我触发数据库更新时,无论是保存还是删除,我都会收到此错误:

Cannot access a disposed object. Object name: 'IServiceProvider'

有时会在第一次尝试时发生,有时在后续尝试时发生。我似乎找不到模式。 我确实设法做的是在调用 await _applicationDbContext.SaveChangesAsync(cancellationToken); 的处理程序中打断点,尽管错误实际上是在 Controller 中引发的,在 await _mediator.Send(someRequestModel); 。引发错误后,应用程序进入中断模式并崩溃。

我将使用虚拟名称,但我认为这是相关代码:

Controller :

public MyController(IMediator mediator)
{
    _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
}

[HttpDelete("{id}")]
public async void Delete(string id)
{
    await _mediator.Send(new DeleteRequestModel(Guid.Parse(id))); // error thrown here
}

处理程序:

public class DeleteCommandHandler : IRequestHandler<DeleteRequestModel>
{
    private readonly ApplicationDbContext _applicationDbContext;

    public DeleteCommandHandler(ApplicationDbContext applicationDbContext)
    {
        _applicationDbContext = applicationDbContext;
    }

    public async Task<Unit> Handle(DeleteRequestModel request, CancellationToken cancellationToken)
    {
        var item = _applicationDbContext.MyData.First(x => x.Id == request.Id);
        _applicationDbContext.MyData.Remove(item);

        await _applicationDbContext.SaveChangesAsync(cancellationToken); // pretty sure this errors out

        return Unit.Value;
    }
}

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnectionString")));
    services.AddDbContext<ApplicationAspNetUsersDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnectionString")));

    services.AddDatabaseDeveloperPageExceptionFilter();

    services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationAspNetUsersDbContext>();

    services.AddIdentityServer()
        .AddApiAuthorization<ApplicationUser, ApplicationAspNetUsersDbContext>();

    services.AddAuthentication()
        .AddIdentityServerJwt();
    services.AddControllers();
    services.AddRazorPages();
    // In production, the Angular files will be served from this directory
    services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; });

    services.AddSwaggerDocument();

    services.AddMediatR(AppDomain.CurrentDomain.Load("MySolution.MyProject.EntityFramework"));
    services.AddValidatorsFromAssembly(AppDomain.CurrentDomain.Load("MySolution.MyProject"));
    services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidatorPipelineBehavior<,>));

    services.AddSingleton(x =>
        new BlobServiceClient(Configuration.GetConnectionString("AzureBlobStorageConnection")));
    services.AddApplicationInsightsTelemetry(Configuration["APPINSIGHTS_CONNECTIONSTRING"]);

    services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));
    services.Configure<AzureBlobStorage>(Configuration.GetSection("AzureBlobStorage"));
    services.Configure<ApplicationInsights>(Configuration.GetSection("ApplicationInsights"));
}

最后,这是堆栈跟踪,这次是更新操作:

at Microsoft.Extensions.DependencyInjection.ServiceLookup.ThrowHelper.ThrowObjectDisposedException()
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at MediatR.Pipeline.RequestExceptionActionProcessorBehavior`2.GetActionsForException(Type exceptionType, TRequest request, MethodInfo& actionMethodInfo)
at MediatR.Pipeline.RequestExceptionActionProcessorBehavior`2.<Handle>d__2.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()   
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at MediatR.Pipeline.RequestPostProcessorBehavior`2.<Handle>d__2.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()   
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at MediatR.Pipeline.RequestPreProcessorBehavior`2.<Handle>d__2.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()   
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)   
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at MySolution.Web.Controllers.MyController.< Patch >d__7.MoveNext() in
..\Controllers\MyController.cs:line 85

非常感谢任何帮助。

最佳答案

您在 Controller 中使用了异步 void。 Async void 应该只在特定场景中使用,在这种情况下,您应该使用 Task 作为返回类型。

关于c# - 无法访问已处置的对象。对象名称 : 'IServiceProvider' error in AspNet Core/EF Core project,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67794528/

相关文章:

c# - C# OOP 说明

c# - ASP.NET MVC URL 生成性能

c# - 传递异步委托(delegate)的方法签名是什么?

c# - 如何在 ASP.NET Core 中获取 TLS/SSL 相关信息?

java - Guice:正确注入(inject)工厂生成的实例

python - 寻找一种有效的方法或算法来检查文件是否属于某个文件夹路径列表中的某个项目

azure - 应用服务计划在 azure devops 中的发布管道期间无法覆盖应用程序设置中的嵌套 JSON 键

c# - 如何使用 |DataDirectory|用 asp.net 核心替换 appsettings.json 中的字符串?

android - 为什么 fragment 的父级在暂停后为空?

dependency-injection - 如何用 Dagger 初始化网络应用程序?