(原)NET CORE3.0 自动注入AppSetting.json文件

原文链接地址: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);
}

原文地址:https://www.cnblogs.com/ruyun/p/12201443.html