Asp.Net Core 扩展IOC注入Attribute

IOC批量注入再Core框架中还是比较麻烦的,因此写了一个简单的IOC注入通过属性标注服务,再通过service自带的注册服务,扩展了三个注入服务,分别为
AddTransientList/AddScopedList/AddSingletonList 下面直接上代码

ServiceInjectExtensions类

    public static class ServiceInjectExtensions
    {
        public static void AddTransientList(this IServiceCollection services, System.Reflection.Assembly assembly)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            foreach (Type item in assembly.GetTypes())
            {
                if (item.GetCustomAttributes(typeof(Transient)).Count() > 0)
                {
                    if (!item.IsInterface)
                    {
                        services.AddTransient(item.GetInterfaces()[0], item);
                    }
                }
            }
        }

        public static void AddScopedList(this IServiceCollection services, System.Reflection.Assembly assembly)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            foreach (Type item in assembly.GetTypes())
            {
                if (item.GetCustomAttributes(typeof(Scoped)).Count() > 0)
                {
                    if (!item.IsInterface)
                    {
                        services.AddTransient(item.GetInterfaces()[0], item);
                    }
                }
            }
        }

        public static void AddSingletonList(this IServiceCollection services, System.Reflection.Assembly assembly)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            foreach (Type item in assembly.GetTypes())
            {
                if (item.GetCustomAttributes(typeof(Singleton)).Count() > 0)
                {
                    if (!item.IsInterface)
                    {
                        services.AddTransient(item.GetInterfaces()[0], item);
                    }
                }
            }
        }
    }

自定义属性

  public class Transient : Attribute
    {
    }

    public class Singleton : Attribute
    {
    }

    public class Scoped : Attribute
    {
    }

再startup类调用服务

  services.AddTransientList(Assembly.GetExecutingAssembly());
  services.AddScopedList(Assembly.GetExecutingAssembly());
  services.AddSingletonList(Assembly.GetExecutingAssembly());

标注服务

    [ExtensionsInject.Transient()]
    public class TestServices : ItestRepository
    {
        public string test()
        {
            return "张三";
        }
    }

再控制器中使用即可,有很多种注入方式,我比较喜欢的这种方式

原文地址:https://www.cnblogs.com/SuperDust/p/13174134.html