I’m using ASP.NET Core’s WebApplicationFactory<T>
to run outside-in BDD-style acceptance tests.
One of my tests needed to resolve a scoped service, and I was suprised to find it crashed with an exception.
var factory = new WebApplicationFactory<Startup>();
var service = factory.Server.Services.GetRequiredService<RefreshOrderService>();
The exception:
System.InvalidOperationException: Cannot resolve scoped service 'RefreshOrderService' from root provider.
According to this GitHub comment, this behaviour is by design, as scoped services are only supposed to be resolved within a scope.
The fix then, is to create a scope:
var factory = new WebApplicationFactory<Startup>();
using var scope = factory.Server.Services
.GetService<IServiceScopeFactory>().CreateScope();
var service = scope.ServiceProvider.GetRequiredService<RefreshOrderService>();
I hope that helps someone.
Thanks, man, that helped ;)