System.ObjectDisposedException: '无法访问已处理的对象对象名称:'IServiceProvider' Startup.cs > 配置()主控制器发起DI主控制器使用DI

问题描述

我在 .NET Core 2.1 中使用依赖注入。应用程序按预期工作,只是在一段时间后 IServiceprovider 容器本身被释放并返回 System.ObjectdisposedException: Cannot access a disposed object.\r\nObject name: 'IServiceProvider'. 当这种情况发生时非常随机

Startup.cs > 配置()

public void ConfigureServices(IServiceCollection services)
    {
        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromMinutes(30);
            options.Cookie.HttpOnly = true;
        });

        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .AddJsonFile($"appsettings.{Environment.EnvironmentName}.json",optional: false)
            .AddEnvironmentvariables()
            .Build();

        if (Environment.IsEnvironment("Local"))
        {
            Configuration[$"AppSettings:BasicSymmetricEncryptionKey"] = "XXXXXXX";
        }

        // Todo: Inject scheduler here? services.AddSingleton<IScheduler,DefaultScheduler>();
        services.AddSingleton(configuration);
        var connectionString = configuration.GetConnectionString("BitswapDatabaseContext");

        services.AddDbContext<BitswapDatabaseContext>(options =>
            options.UsesqlServer(connectionString));

        services.AddSingleton<ISystemInfo,LocalSystem>();
        services.AddSingleton<ITokenGenerator<Guid>,GuidTokenSource>();
        services.AddSingleton<IShoppingService,ShoppingService>();
        services.AddSingleton<IEventLogger,LoggerService>();
        services.AddSingleton<System.Reactive.Concurrency.IScheduler>(Scheduler.Default);
        services.AddSingleton<IAccounting,Accounting>();
        services.AddSingleton<IPaymentService,PaymentService>();
        services.AddSingleton<ICardsupplierResolver,CardsupplierResolver>();

        services.AddScoped<iqrCodeService,QRaftClient>();
        services.AddScoped<IMailService,SendGridMailer>();
        services.AddScoped<IEmailVerifier,EmailVerifier>();
        services.AddScoped<IUserService,UserService>();
        services.AddScoped<IBlockChain,TestBlockChain>(); // TO DO: don't use test blockChain
    }

主控制器(发起DI)

private readonly IServiceProvider _serviceProvider;

public Session(IServiceProvider serviceProvider)
{
    _serviceProvider = serviceProvider;
}

主控制器(使用DI)

这是我访问 _serviceProvider 并得到已处理错误的地方:

using (var scope = _serviceProvider.CreateScope())
{
            var database = scope.ServiceProvider.GetrequiredService<BitswapDatabaseContext>();
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)