System.ObjectDisposedException: “Cannot access a disposed context instance [closed]

I get the following error:

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.
Object name: ‘LineDbContext’.”

This is my Program.cs:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddConfiguration(builder);
builder.Services.AddPersistence();
builder.Services.AddBusinessServices();
builder.Services.AddWorker();

builder.Services.AddControllers().AddApplicationPart(typeof(LineController).Assembly);

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder
    .Build()
    .Seed();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.MapControllers();

app.Run();

ServiceExtensions.cs:

public static class ServiceExtensions
{
    public static void AddConfiguration(this IServiceCollection services, WebApplicationBuilder builder)
    {
        var config = builder.Configuration.Get<ApplicationSettings>();

        services.AddOptions();
        services.Configure<ApplicationSettings>(builder.Configuration);
        services.Configure<RabbitMqConnectionModel>(builder.Configuration.GetSection("RabbitMq"));
        services.AddSingleton(config);
    }

    public static void AddPersistence(this IServiceCollection services)
    {
        // Database in Memory. Just for test
        services.AddDbContext<LineDbContext>(opt => opt.UseInMemoryDatabase("ConfigDB"));
        services.AddScoped<LineRepository>();
        services.AddScoped<ILineRepository, LineRepository>();
    }

    public static void AddBusinessServices(this IServiceCollection services)
    {
        services.AddSingleton<RabbitMqConnectionFactory>();
        services.AddTransient<ILineApiService, LineApiService>();
        services.AddTransient<ILineService, LineService>();
    }

    public static void AddWorker(this IServiceCollection services)
    {
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            services.AddWindowsService(options =>
            {
                options.ServiceName = "MightyCall ConfigDb Service";
            });
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
        {
            services.AddSystemd();
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD))
        {
            throw new NotSupportedException($"{nameof(OSPlatform.FreeBSD)} not supported");
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
        {
            throw new NotSupportedException($"{nameof(OSPlatform.OSX)} not supported");
        }
        else
        {
            throw new NotSupportedException("This OS is not supported");
        }

        services.AddHostedService<Worker>();
    }
}

Worker.cs:

public class Worker : BackgroundService
{
    private readonly NLog.ILogger _logger = LogManager.GetCurrentClassLogger();
    private readonly IServiceProvider _serviceProvider;

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

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await InitAsync();
        while (!stoppingToken.IsCancellationRequested)
        {
            await Task.Delay(1000, stoppingToken);
        }
    }

    private async Task InitAsync()
    {
        using var scope = _serviceProvider.CreateScope();

        var _config = scope.ServiceProvider.GetRequiredService<ApplicationSettings>();
        var _factory = scope.ServiceProvider.GetRequiredService<RabbitMqConnectionFactory>();
        var _lineService = scope.ServiceProvider.GetRequiredService<ILineService>();

        var messageService = new MessageGatewayRabbitMq(_config, _factory, _lineService);
        await messageService.InitAsync();
    }
}

MessageGatewayRabbitMq:

public class MessageGatewayRabbitMq
{
    private readonly NLog.ILogger _logger = LogManager.GetCurrentClassLogger();
    private readonly ApplicationSettings _configuration;
    private readonly RabbitMqConnectionFactory _factory;

    private readonly ILineService _lineService;

    // getting from rabbitmq
    private IModel _inChannel;

    // sending to rabbitmq
    private IModel _outChannel;

    public MessageGatewayRabbitMq(
        ApplicationSettings configuration,
        RabbitMqConnectionFactory factory,
        ILineService lineService)
    {
        _lineService = lineService;
        _factory = factory;
        _configuration = configuration;
    }

    public async Task InitAsync()
    {
        _outChannel = _factory.CreateModel();
        _outChannel.ExchangeDeclare(
            exchange: _configuration.RabbitMq.OutgoingExchange,
            type: ExchangeType.Topic,
        durable: true);

        _inChannel = _factory.CreateModel();
        _inChannel.QueueDeclare(
            queue: _configuration.RabbitMq.IncomingQueue,
            exclusive: false,
            autoDelete: false,
            arguments: null);
        _inChannel.ExchangeDeclare(
            exchange: _configuration.RabbitMq.IncomingExchange,
            type: ExchangeType.Topic,
            durable: true);
        _inChannel.QueueBind(
            queue: _configuration.RabbitMq.IncomingQueue,
            exchange: _configuration.RabbitMq.IncomingExchange,
            routingKey: _configuration.RabbitMq.IncomingRoutingKey);

        var consumer = new AsyncEventingBasicConsumer(_inChannel);
        consumer.Received += async (model, ea) =>
        {
            var body = ea.Body.ToArray();
            await ProcessJsonAsync(Encoding.UTF8.GetString(body));
        };

        _inChannel.BasicConsume(
            queue: _configuration.RabbitMq.IncomingQueue,
            autoAck: true,
            consumer: consumer);
    }

    private async Task ProcessJsonAsync(string json)
    {
        try
        {
            JObject jObj = JObject.Parse(json);
            string messageType = (string)jObj["type"];
            var supportedMessageTypes = new string[] { "request.getAllLines", "request.getLineByNodeId" };
            if (!supportedMessageTypes.Contains(messageType))
            {
                throw new Exception($"Unknown message type {messageType}, message {json}");
            }

            if (messageType == "request.getAllLines")
            {
                await ProcessMessageAsync(JsonConvert.DeserializeObject<Message>(json));
            }
        }
        catch (Exception ex)
        {
            _logger.Error(ex.Message);
        }
    }

    private async Task ProcessMessageAsync(Message message)
    {
        if (message.Type == "request.getAllLines")
        {
            var lines = await _lineService.GetAllAsync();
            SendMessage(message.RequestId, lines);
        }
    }

    private void SendMessage(string requestId, IEnumerable<Line> lines)
    {
        Send(
            routingKey: _configuration.RabbitMq.OutgoingRoutingKey,
            json: JsonConvert.SerializeObject(new Message
            {
                Type = "response.getAllLines",
                RequestId = requestId,
                Content = JsonConvert.SerializeObject(lines),
                Date = new DateTimeOffset(DateTime.UtcNow, TimeSpan.Zero).ToUnixTimeSeconds()
            }));
    }

    private void Send(string routingKey, string json)
    {
        _logger.Debug($"Sending: {json}");
        _outChannel.BasicPublish(
            exchange: _configuration.RabbitMq.OutgoingExchange,
            routingKey: routingKey,
            basicProperties: null,
            body: Encoding.UTF8.GetBytes(json));
    }
}

I have already tried different methods of dependency injection

1

using var scope = _serviceProvider.CreateScope();

This disposes the scope when the method ends. That in turn will likely dispose one of the dependencies of MessageGatewayRabbitMq. That should also most likely be disposable since it seem to own disposable objects.

you probably want to:

  1. Move the CreateScope to the ExecuteAsync
  2. Make MessageGatewayRabbitMq disposable
  3. Make InitAsync return the created message gateway so it can be disposed.

Keep in mind that everything that implements IDisposable should be disposed, and in the reverse order of creation.

I would also consider refactoring the code to get rid of InitAsync, for example by creating a MessageGatewayRabbitMqFactory that is responsible for creating and fully initializing the MessageGatewayRabbitMq. Such a factory could be registered in the DI container, simplifying construction and disposal.

At the moment it helped me at all levels to get services from IServiceScopeFactory. That is, in Repository, Service, and in MessageGatewayRabbitMq in the constructor there is only IServiceScopeFactory serviceScopeFactory

It is looks like this:

   public sealed class Worker(IServiceScopeFactory serviceScopeFactory) : BackgroundService
   {
      protected override async Task ExecuteAsync(CancellationToken stoppingToken)
      {
          await DoWorkAsync(stoppingToken);
      }

      private async Task DoWorkAsync(CancellationToken stoppingToken)
      {
          using (IServiceScope scope = serviceScopeFactory.CreateScope())
          {
              MessageGatewayRabbitMq messageGateway = scope.ServiceProvider.GetRequiredService<MessageGatewayRabbitMq>();
              await messageGateway.StartListeningAsync();
          }
      }
   }

and all other services are obtained from the created scope

Use scoped services within a Background Service

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