码迷,mamicode.com
首页 > Web开发 > 详细

asp.net core 通过自定义容器获取DI容器中的类型

时间:2019-11-16 23:21:50      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:not   获取ip   current   容器   code   ogg   ilog   cep   初始化   

1.自定义容器,意在通过组合方式注入获取Iprovider

 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<T>()
28         {
29             return _serviceProvider.GetService<T>();
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<CustomAutofacAop> _logger;
2         public CustomAutofacAop()
3         {
4             _logger = AppDependencyResolver.Current.GetService<ILogger<CustomAutofacAop>>();
5 
6         }

 

 

asp.net core 通过自定义容器获取DI容器中的类型

标签:not   获取ip   current   容器   code   ogg   ilog   cep   初始化   

原文地址:https://www.cnblogs.com/Spinoza/p/11874463.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!