asp.NetcoreカスタムコンテナからDIコンテナのタイプを取得
5413 ワード
1.Iproviderを組み合わせて注入することを意図したカスタムコンテナ
2.startup初期化容器、ここでautofacのprovider
3.呼び出し
1 public class AppDependencyResolver
2 {
3 private static AppDependencyResolver _resolver;
4
5 public static AppDependencyResolver Current
6 {
7 get
8 {
9 if (_resolver == null)
10 throw new Exception("AppDependencyResolver not initialized. You should initialize it in Startup class");
11 return _resolver;
12 }
13 }
14
15 public static void Init(IServiceProvider services)
16 {
17 _resolver = new AppDependencyResolver(services);
18 }
19
20 private readonly IServiceProvider _serviceProvider;
21
22 public object GetService(Type serviceType)
23 {
24 return _serviceProvider.GetService(serviceType);
25 }
26
27 public T GetService()
28 {
29 return _serviceProvider.GetService();
30 }
31
32 private AppDependencyResolver(IServiceProvider serviceProvider)
33 {
34 _serviceProvider = serviceProvider;
35 }
36 }
2.startup初期化容器、ここでautofacのprovider
1 AppDependencyResolver.Init(provider);
3.呼び出し
1 private ILogger _logger;
2 public CustomAutofacAop()
3 {
4 _logger = AppDependencyResolver.Current.GetService>();
5
6 }