Skip to content

Commit 8005d1a

Browse files
authored
Merge pull request #374 from json-api-dotnet/fix/#362
fix(#362): improve error message for null HttpContext
2 parents c33c455 + eb2d9e9 commit 8005d1a

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

src/JsonApiDotNetCore/Services/ScopedServiceProvider.cs

+12-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
using JsonApiDotNetCore.Internal;
12
using Microsoft.AspNetCore.Http;
23
using System;
34

@@ -23,6 +24,16 @@ public RequestScopedServiceProvider(IHttpContextAccessor httpContextAccessor)
2324
}
2425

2526
/// <inheritdoc />
26-
public object GetService(Type serviceType) => _httpContextAccessor.HttpContext.RequestServices.GetService(serviceType);
27+
public object GetService(Type serviceType)
28+
{
29+
if (_httpContextAccessor.HttpContext == null)
30+
throw new JsonApiException(500,
31+
"Cannot resolve scoped service outside the context of an HTTP Request.",
32+
detail: "If you are hitting this error in automated tests, you should instead inject your own "
33+
+ "IScopedServiceProvider implementation. See the GitHub repository for how we do this internally. "
34+
+ "https://github.com/json-api-dotnet/JsonApiDotNetCore/search?q=TestScopedServiceProvider&unscoped_q=TestScopedServiceProvider");
35+
36+
return _httpContextAccessor.HttpContext.RequestServices.GetService(serviceType);
37+
}
2738
}
2839
}

0 commit comments

Comments
 (0)