原文鏈接地址:https://www.cnblogs.com/ruyun/p/12201443.html
- 說明
早先的時候使用DOTNET CORE2.0時,AppSetting.json中文件注入DI時,都是進行手動配置
services.Configure<AppSettingTest>(Configuration.GetSection("Test"));
這樣有可能會遺忘,在啟動項目出現異常才發現。使用起來也不是很方便。
那有沒有比較方便的方式呢?在研究MediatR源碼時受到啟發,寫了一段可以自動注入的幫助類
- 具體實現
定義一個借口,結構如下:
public interface IAutoAppSetting
{
}
需要自動注入的AppSetting對象需要繼承改借口,主要作用是方便后期反射時動態查找實現類。
定義特性,配置AppSetting中節點名稱
public class AutoConfig : Attribute
{
public string Key { get; set; }
}
新建兩個IAutoAppSetting的實現類
[AutoConfig(Key = "Authorization")]
public class Test : IAutoAppSetting
{
public string Tv { get; set; }
}
[AutoConfig(Key = "Test2")]
public class Test2 : IAutoAppSetting
{
public int Tv2 { get; set; }
}
利用泛型來實現動態注入,代碼參考MediatR源碼
public abstract class AutoConfigurationWrapper
{
public abstract void Register(IServiceCollection services, string appSettingKey);
}
public class AutoConfigurationWrapperImpl<TConfiguration> : AutoConfigurationWrapper where TConfiguration : class, IAutoAppSetting
{
public override void Register(IServiceCollection services, string appSettingKey)
{
var configuration = services.BuildServiceProvider().GetService<IConfiguration>();
services.Configure<TConfiguration>(configuration.GetSection(appSettingKey));
}
}
利用反射查到到所有IAutoAppSetting的實現類
// 示例代碼
List<Type> types = new List<Type>{
typeof(Test),typeof(Test2)
}
foreach (var item in types)
{
var attribute = item.GetCustomAttribute<AutoConfig>();
// 沒有在特性中標明節點名稱,則默認使用類名
var appSettingKey = (attribute == null)
? item.Name
: attribute.Key;
// 動態構建泛型類,使用注入DI
var type = typeof(AutoConfigurationWrapperImpl<>).MakeGenericType(item);
var wrapper = (AutoConfigurationWrapper)Activator.CreateInstance(type);
wrapper.Register(services, appSettingKey);
}