在開發.NET Core web服務的時候,我們習慣使用自帶的依賴注入容器來進行注入。
于是就會經常進行一個很頻繁的的重復動作:定義一個接口->寫實現類->注入
有時候會忘了寫Add這一步,看到屏幕上的報錯一臉懵逼,然后瞬間反應過來忘了注入了。趕緊補上serviceCollection.AddXXX這句話
雖然說有很多開源框架已經實現了類似的工作,比如AutoFac,Unity等依賴注入框架。但是這些庫都太龐大了,我個人還是喜歡輕量級的實現。
定義一個枚舉
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false )] public class AutoInjectAttribute : Attribute { public AutoInjectAttribute(Type interfaceType, InjectType injectType) { Type = interfaceType; InjectType = injectType; } public Type Type { get ; set ; } /// <summary> /// 注入類型 /// </summary> public InjectType InjectType { get ; set ; } } |
定義三種注入類型
1
2
3
4
5
6
7
8
9
10
|
/// <summary> /// 注入類型 /// </summary> public enum InjectType { Scope, Single, Transient } |
掃描運行目錄下所有的dll,進行自動注入
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
43
44
|
/// <summary> /// 自動依賴注入 /// </summary> public static class AutoInject { /// <summary> /// 自動注入所有的程序集有InjectAttribute標簽 /// </summary> /// <param name="serviceCollection"></param> /// <returns></returns> public static IServiceCollection AddAutoDi( this IServiceCollection serviceCollection) { var path = AppDomain.CurrentDomain.BaseDirectory; var assemblies = Directory.GetFiles(path, "*.dll" ).Select(Assembly.LoadFrom).ToList(); foreach (var assembly in assemblies) { var types = assembly.GetTypes().Where(a => a.GetCustomAttribute<AutoInjectAttribute>() != null ) .ToList(); if (types.Count <= 0) continue ; foreach (var type in types) { var attr = type.GetCustomAttribute<AutoInjectAttribute>(); if (attr?.Type == null ) continue ; switch (attr.InjectType) { case InjectType.Scope: serviceCollection.AddScoped(attr.Type, type); break ; case InjectType.Single: serviceCollection.AddSingleton(attr.Type, type); break ; case InjectType.Transient: serviceCollection.AddTransient(attr.Type, type); break ; default : throw new ArgumentOutOfRangeException(); } } } return serviceCollection; } } |
使用自動依賴注入功能
1
2
3
4
5
|
public void ConfigureServices(IServiceCollection services) { services.AddAutoDi(); } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public interface ITest { string Say(); } [AutoInject( typeof (ITest),InjectType.Scope)] public class Test : ITest { public String Say() { return "test:" +DateTime.Now.ToString(); } } |
再次運行程序,所有的貼有AutoInject
的所有的實現類,都會被注入到asp.net core的依賴注入容器中。
以上就是ASP.NET Core實現自動依賴注入的詳細內容,更多關于ASP.NET Core 自動依賴注入的資料請關注服務器之家其它相關文章!
原文鏈接:https://www.cnblogs.com/boxrice/p/14664424.html