-
Notifications
You must be signed in to change notification settings - Fork 3
/
ServiceProviderDependencyResolver.cs
42 lines (33 loc) · 1.64 KB
/
ServiceProviderDependencyResolver.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
namespace Arex388.AspNet.Mvc.Startup {
internal sealed class ServiceProviderDependencyResolver :
IDependencyResolver {
public object GetService(
Type serviceType) {
var scope = HttpContext.Current.GetServiceScope();
if (scope is null) {
throw new InvalidOperationException("IServiceScope was not provided. If this method is being called directly or indirectly from an async sequence of methods that use ConfigureAwait(false), then you're probably loosing the HttpContext.Current due to the thread switch.");
}
return scope.ServiceProvider.GetService(serviceType);
}
public IEnumerable<object> GetServices(
Type serviceType) {
var scope = HttpContext.Current.GetServiceScope();
if (scope is null) {
throw new InvalidOperationException("IServiceScope was not provided. If this method is being called directly or indirectly from an async sequence of methods that use ConfigureAwait(false), then you're probably loosing the HttpContext.Current due to the thread switch.");
}
return scope.ServiceProvider.GetServices(serviceType);
}
internal static void EnsureConfigured() {
if (DependencyResolver.Current is ServiceProviderDependencyResolver) {
return;
}
var resolver = new ServiceProviderDependencyResolver();
DependencyResolver.SetResolver(resolver);
}
}
}