UseServiceScope in AspNetCore DI fails with exception
See original GitHub issueIs this a bug report?
Yes
Can you also reproduce the problem with the latest version?
Yes, it fails in both the latest release and the current preview.
Environment
- Operating system: Windows 10
- Visual Studio version: VS 2017
- Dotnet version: .NET Core 2.2
Steps to Reproduce
(Write your steps here:)
- Using startup like this example
services.AddMassTransit(provider =>
Bus.Factory.CreateUsingAzureServiceBus(cfg =>
{
cfg.UseServiceScope(provider);
var host = cfg.Host(Configuration.GetValue<string>("ServiceBus:ConnectionString"), sbcfg => { });
cfg.ReceiveEndpoint("test-queue", e =>
{
e.UseMessageRetry(c => c.Immediate(5));
e.Consumer<TestConsumer>(provider);
});
}),
x =>
{
x.AddConsumer<TestConsumer>();
}
);
- Publish a message to the queue.
- The consumer will fail with
fail: MassTransit.Messages[0] R-FAULT sb://edgepoc.servicebus.windows.net/test-queue 36040000-dfb5-5428-cb4e-08d6bdeba4c8 Common.ITestMessage TestUseServiceScope.Worker.TestConsumer(00:00:00.0004802) The ConsumeContext was already set. System.InvalidOperationException: The ConsumeContext was already set. at MassTransit.Scoping.ScopedConsumeContextProvider.SetContext(ConsumeContext context) at MassTransit.ExtensionsDependencyInjectionIntegration.ScopeProviders.DependencyInjectionConsumerScopeProvider.MassTransit.Scoping.IConsumerScopeProvider.GetScope[TConsumer,T](ConsumeContext`1 context)
- Removing the UseServiceScope line stops this behaviour.
Expected Behavior
Message consumed successfully.
Actual Behavior
Failed with
fail: MassTransit.Messages[0] R-FAULT sb://edgepoc.servicebus.windows.net/test-queue 36040000-dfb5-5428-cb4e-08d6bdeba4c8 Common.ITestMessage TestUseServiceScope.Worker.TestConsumer(00:00:00.0004802) The ConsumeContext was already set. System.InvalidOperationException: The ConsumeContext was already set. at MassTransit.Scoping.ScopedConsumeContextProvider.SetContext(ConsumeContext context) at MassTransit.ExtensionsDependencyInjectionIntegration.ScopeProviders.DependencyInjectionConsumerScopeProvider.MassTransit.Scoping.IConsumerScopeProvider.GetScope[TConsumer,T](ConsumeContext`1 context)
Reproducible Demo
https://github.com/steverash/TestUseServiceScope
Included a demo aspnetcore app to show the startup and consumer. Also a console app to publish a message to test.
Issue Analytics
- State:
- Created 4 years ago
- Comments:9 (5 by maintainers)

Top Related StackOverflow Question
@Crozin the less I use DI containers in my code, the better I sleep at night…
@Crozin doubtful, as those type of abstractions end up creating more hassle than they’re worth, particularly when there is already the Microsoft.Extensions abstraction, which if anything would be the one supported somehow.