Add the following code after you done with your container builder to see the truth:
foreach (var service in builder.Services)
{
Console.WriteLine($"Service: {service.ServiceType.Name}, Lifetime: {service.Lifetime}");
}
Spoiler: as you will see, despite what Mediatr docs saying, everything is Singleton. And to my knowledge, this is not configurable, so you have to inject some kind of factories instead of scoped dependencies directly.
Here's my take on this:
private static IServiceCollection AddScopedFactory<T>(this IServiceCollection services) where T : class
{
return services.AddSingleton<Func<T>>(s => () =>
s.GetRequiredService<IHttpContextAccessor>()
.HttpContext!
.RequestServices
.GetRequiredService<T>());
}
And then you can just register your precious EF context like this:
services.AddScopedFactory<MyCoolDbContext>();
Mediatr handler dependency will be Func<MyCoolDbContext> _getContext;
and you just inject it and call it to obtain that context wherever needed inside handler.