Quantcast
Channel: mattfrear – Matt's work blog
Viewing all articles
Browse latest Browse all 43

TestServer cannot resolve scoped service

0
0

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.


Viewing all articles
Browse latest Browse all 43

Latest Images

Trending Articles





Latest Images