TestServer cannot resolve scoped service

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.

Advertisement

One thought on “TestServer cannot resolve scoped service

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s