Summary
The RegisterMediator extension method in Mediator.Net.MicrosoftDependencyInjection creates a new IServiceScope when IMediator is resolved, causing handlers to resolve dependencies from a different scope than the current request/operation. This breaks transactions and causes issues with scoped services like DbContext.
Problem: When IMediator is resolved, it creates a new scope (x.CreateScope()), and all handlers subsequently resolve their dependencies from this new scope instead of the current request/operation scope.
Also, maybe I am missing something and using the package/registration incorrectly.
Expected Behavior
Handlers should resolve dependencies from the same scope as the rest of the request/operation to ensure:
- The same
DbContext instance is shared across the request
- Transactions work correctly
- Scoped services maintain consistency
Current Workaround
Creating a custom IDependencyScope implementation that accepts IServiceProvider
// Custom adapter that doesn't create a new scope
private sealed class CurrentScopeDependencyAdapter : IDependencyScope
{
private readonly IServiceProvider _serviceProvider;
private readonly IServiceScope? _ownedScope;
public CurrentScopeDependencyAdapter(IServiceProvider serviceProvider)
=> _serviceProvider = serviceProvider;
private CurrentScopeDependencyAdapter(IServiceScope scope)
{
_ownedScope = scope;
_serviceProvider = scope.ServiceProvider;
}
public T Resolve<T>() where T : notnull
=> _serviceProvider.GetRequiredService<T>();
public object Resolve(Type t)
=> _serviceProvider.GetRequiredService(t);
public IDependencyScope BeginScope()
{
var scope = _serviceProvider.CreateScope();
return new CurrentScopeDependencyAdapter(scope);
}
public void Dispose() => _ownedScope?.Dispose();
}
Summary
The
RegisterMediatorextension method inMediator.Net.MicrosoftDependencyInjectioncreates a newIServiceScopewhenIMediatoris resolved, causing handlers to resolve dependencies from a different scope than the current request/operation. This breaks transactions and causes issues with scoped services likeDbContext.Problem: When
IMediatoris resolved, it creates a new scope (x.CreateScope()), and all handlers subsequently resolve their dependencies from this new scope instead of the current request/operation scope.Also, maybe I am missing something and using the package/registration incorrectly.
Expected Behavior
Handlers should resolve dependencies from the same scope as the rest of the request/operation to ensure:
DbContextinstance is shared across the requestCurrent Workaround
Creating a custom
IDependencyScopeimplementation that acceptsIServiceProvider