6/14/2023 0 Comments Masstransit autofac fault![]() Keep the scope as small as possible to avoid errors that are caused by to much reuse, or long life time. ![]() For example when you have a dbcontext, the objects life time will be the same as the scope where it is created. When using a scoped service in a IHostedService it is important you think about why it is scoped. Using (var scope = _serviceScopeFactory.CreateScope()) Protected override Task ExecuteAsync(CancellationToken stoppingToken) _serviceScopeFactory = serviceScopeFactory Public Class(IServiceScopeFactory serviceScopeFactory) Public IServiceScopeFactory _serviceScopeFactory Public class BackgroundServiceConsumeScopedService : BackgroundService, IHostedService Within this scope you can use the scoped services. To use a scoped object in a IHostedService you have to create dependency injection scope with the IServiceScopeFactory. ![]() As result of this you cannot create dependencies declared as scoped. The exception is thrown because the IHostedService singleton itself is not created in a dependency injection scope. Your program throws the InvalidOperationException when it is started. You are implementing a IHostedService and inject a dependency that is scoped (for example a DbContext). System.InvalidOperationException: ‘Cannot consume scoped service ‘’ from singleton ‘’.’ When injecting a scoped service into a IHostedService you get the following error: This blog post will help you to resolve the problem faster. Mjolnir - Hystrix-inspired fault tolerance with circuit breakers and. The first time you get this exception, it is takes some time to figure out what is going on. MassTransit - A distributed application framework for RabbitMQ and Azure Service. What I have seen is that when injecting a scoped service into the IHostedService you get a InvalidOperationException on startup. In our projects we are using IHostedService to run background processes. Episode Twelve covers error handling, including fault events published by MassTransit, as well as moving faulted messages to the error queue.
0 Comments
Leave a Reply. |