diff --git a/src/JsonApiDotNetCore/Services/ScopedServiceProvider.cs b/src/JsonApiDotNetCore/Services/ScopedServiceProvider.cs index eecd554e7c..51248f7593 100644 --- a/src/JsonApiDotNetCore/Services/ScopedServiceProvider.cs +++ b/src/JsonApiDotNetCore/Services/ScopedServiceProvider.cs @@ -1,3 +1,4 @@ +using JsonApiDotNetCore.Internal; using Microsoft.AspNetCore.Http; using System; @@ -23,6 +24,16 @@ public RequestScopedServiceProvider(IHttpContextAccessor httpContextAccessor) } /// - public object GetService(Type serviceType) => _httpContextAccessor.HttpContext.RequestServices.GetService(serviceType); + public object GetService(Type serviceType) + { + if (_httpContextAccessor.HttpContext == null) + throw new JsonApiException(500, + "Cannot resolve scoped service outside the context of an HTTP Request.", + detail: "If you are hitting this error in automated tests, you should instead inject your own " + + "IScopedServiceProvider implementation. See the GitHub repository for how we do this internally. " + + "https://github.com/json-api-dotnet/JsonApiDotNetCore/search?q=TestScopedServiceProvider&unscoped_q=TestScopedServiceProvider"); + + return _httpContextAccessor.HttpContext.RequestServices.GetService(serviceType); + } } }