System.ObjectDisposedException: Cannot access a disposed context instance

I have a problem occurring when I execute “await alarmHandler.InitRedis(“setting”);”:”System.ObjectDisposedException: Cannot access a disposed context instance. A common cause of this error is disposing a context instance 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 instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.”

This is my code:

  1. program.cs
c#
builder.Services.AddHostedService<Alarm>();
builder.Services.AddScoped<AlarmHnadler>();
  1. Alarm
c#
public class Alarm : IHostedService, IDisposable
{
    private readonly MqttFactory mqttFactory;
    private readonly MqttBrokerOptions? _mqttBrokerOptions;
    private readonly IoTDbContext _context;
    private readonly RabbitMQSet _rabbitMQSet;
    private readonly IDbContextFactory<IoTDbContext> _dbContextFactory;
    private readonly IMapper _mapper;
    private  AlarmHnadler alarmHandler;
    private readonly IServiceScopeFactory _serviceScopeFactory;
    private IModel? _channel { get; set; }
    private readonly RedisUtils _redisUtils;

    public Alarm(IModel channel, IOptions<MqttBrokerOptions> mqttBrokerOptions, IConfiguration configuration,
        SmsClient smsClient, VoiceMessagingService voiceMessagingService,
        IDbContextFactory<IoTDbContext> dbContextFactory, IMapper mapper,
        IHubContext<AlarmHub> hubContext,IServiceScopeFactory serviceScopeFactory)
    {
        mqttFactory = new MqttFactory();
        _mqttBrokerOptions = mqttBrokerOptions.Value;
        _dbContextFactory = dbContextFactory;
        _context = dbContextFactory.CreateDbContext();
        _channel = channel;
        _mapper = mapper;
        _redisUtils = new RedisUtils(configuration, _context, _mapper);
        _serviceScopeFactory = serviceScopeFactory;
        using (var scope = _serviceScopeFactory.CreateScope())
        {
             alarmHandler = scope.ServiceProvider.GetRequiredService<AlarmHnadler>();
        }
       
        
    }
public async Task StartAsync(CancellationToken cancellationToken)
    {
        var userName = "Server";
        var password = "123456".AESEncrypt(mode: CipherMode.ECB, padding: PaddingMode.Zeros, base64: false);
        var mqttClientOptions = new MqttClientOptionsBuilder()
            .WithTcpServer(_mqttBrokerOptions?.Host, _mqttBrokerOptions?.Port)
            .WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V500)
            .WithCredentials(userName, password)
            .WithCleanSession()
            .Build();
        MqttSet.Client = mqttFactory.CreateMqttClient();
        MqttSet.Client.ConnectedAsync += Client_ConnectedAsync;
        MqttSet.Client.DisconnectedAsync += Client_DisconnectedAsync;
        MqttSet.Client.ApplicationMessageReceivedAsync += Client_ApplicationMessageReceivedAsync;
        await MqttSet.Client.ConnectAsync(mqttClientOptions, CancellationToken.None);
       
            await alarmHandler.InitRedis("setting");
      
        
    }

AlarmHnadler

c#
 public class AlarmHnadler : ControllerBase
    {
        private readonly IConfiguration _configuration;
        private readonly SmsClient _smsClient;
        private readonly VoiceMessagingService _voiceMessagingService;
        private readonly IoTDbContext _context;
        private readonly IDbContextFactory<IoTDbContext> _dbContextFactory;
        private readonly IMapper _mapper;
        private readonly IDatabase _redisDB;
        private readonly AlarmUtils _alarmUtil;
        private readonly RedisUtils _redisUtils;
        private Dictionary<string, string> gatewaytAlarmDict { get; set; }
        private readonly IHubContext<AlarmHub> _hubContext;

        private IModel? _channel { get; set; }
        public IBatch batch { get; set; }

        public AlarmHnadler(IModel channel, IDbContextFactory<IoTDbContext> dbContextFactory,
            IConfiguration configuration, IHubContext<AlarmHub> hubContext,
            IMapper mapper, SmsClient smsClient, VoiceMessagingService voiceMessagingService)
        {
            _configuration = configuration;
            _dbContextFactory = dbContextFactory;
            _alarmUtil = new AlarmUtils(_configuration);
            var settingValue = _configuration["RedisDb"];
            _channel = channel;
            int.TryParse(settingValue, out int result);
            _redisDB = RedisClient.GetDatabase(result);
            _context = dbContextFactory.CreateDbContext();
            _smsClient = smsClient;
            _voiceMessagingService = voiceMessagingService;
            _mapper = mapper;
            gatewaytAlarmDict = new Dictionary<string, string>();
            _hubContext = hubContext;
            setGatewayAlarmDictValue();
            batch = _redisDB.CreateBatch();
            _redisUtils = new RedisUtils(_configuration, _context, _mapper);
        }
          public async Task InitRedis(string tableName)
        {
            switch (tableName)
            {
                case "setting":
                    batch.KeyDeleteAsync("setting");
                    var alarmPointSettings =
                        await _context.Set<AlarmPointSettings>().Where(a => a.Status == 1).ToListAsync();
                    var result =
                        _mapper.Map<List<AlarmPointSettings>, List<AlarmPointSettingsRedis>>(alarmPointSettings);
                    var settingR = result.Select(item => JsonConvert.SerializeObject(item))
                        .Select((json, index) => new { Id = alarmPointSettings[index].Id.ToString(), Json = json })
                        .ToList();
                    foreach (var r in settingR)
                    {
                        batch.HashSetAsync("setting", r.Id, r.Json);
                    }

                    batch.Execute();
                    break;
}

If you could help me solve this problem, I would be very grateful.

I no longer inject the context directly; instead, I use ContextFactory to generate it.I think this problem was solved.But i dont’t know why.The area circled in red in the image below is my modification.
enter image description here
ps:I initially didn’t use dependency injection; instead, I directly instantiated objects (using ‘new’), which also worked.Like this

c#
// alarmHandler = new AlarmHnadler(_channel, _dbContextFactory, configuration, hubContext,
        //     _context, _mapper, smsClient, voiceMessagingService);

New contributor

slim shady is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật