• 几十行代码实现ASP.NET Core自动依赖注入


    在开发.NET Core web服务的时候,我们习惯使用自带的依赖注入容器来进行注入。

    于是就会经常进行一个很频繁的的重复动作:定义一个接口->写实现类->注入

    有时候会忘了写Add这一步,看到屏幕上的报错一脸懵逼,然后瞬间反应过来忘了注入了。赶紧补上serviceCollection.AddXXX这句话

    虽然说有很多开源框架已经实现了类似的工作,比如AutoFac,Unity等依赖注入框架。但是这些库都太庞大了,我个人还是喜欢轻量级的实现。

    定义一个枚举

    
    [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; }
        }
    
    

    定义三种注入类型

    
    /// <summary>
        /// 注入类型
        /// </summary>
        public enum InjectType
        {
            Scope,
            Single,
            Transient
        }
    
    

    扫描运行目录下所有的dll,进行自动注入

    
    /// <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;
            }
        }
    
    

    使用自动依赖注入功能

    
       public void ConfigureServices(IServiceCollection services)
            {
                services.AddAutoDi();
            }
    
    
    
      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的依赖注入容器中。

    欢迎关注我的公众号 青城同学 ,不定时和你分享一些技术和有趣的事情。

  • 相关阅读:
    01 Jq 基础
    01 属性
    input 编辑框 光标 的相关问题
    登录页面 文字 2 3 4 个字 等宽俩端对齐 空格
    复选框单选框与文字对齐问题的研究与解决
    在Python中对MySQL中的数据进行可视化
    输入2个坐标的数值求出对应坐标间的距离和圆的面积
    numpy中arange函数内起始值必须大于结束值,否则生成为空的一维数组
    条件语句练习-比分预测
    三元表达式是棒棒哒!
  • 原文地址:https://www.cnblogs.com/boxrice/p/14664424.html
Copyright © 2020-2023  润新知