skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    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


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search