.NET8/.NETCore 依赖注入:自动注入项目中所有接口和自定义类

.NET8/.NETCore 依赖接口注入:自动注入项目中所有接口和自定义类

目录

自定义依赖接口

需要依赖注入的类必须实现以下接口。

C#

    /// <summary>
    /// 依赖接口
    /// </summary>
    public interface IDependency { }

    /// <summary>
    /// 注入接口,生命周期:Transient
    /// </summary>
    public interface ITransientDependency : IDependency { }

    /// <summary>
    /// 注入接口,生命周期:Scoped
    /// </summary>
    public interface IScopedDependency : IDependency { }

    /// <summary>
    /// 注入接口,生命周期:Singleton
    /// </summary>
    public interface ISingletonDependency : IDependency { }

扩展类:HostExtensions AddInjectionServices方法

C#

 public static class HostExtensions
 {
     /// <summary>
     /// 自动注入接口, 注入到服务容器IServiceCollection
     /// </summary>
     /// <param name="services"></param>
     /// <returns></returns>
     public static IServiceCollection AddInjectionServices(this IServiceCollection services)
     {
         //服务生命周期映射
         Dictionary<Type, ServiceLifetime> map = new Dictionary<Type, ServiceLifetime>
         {
             { typeof(ITransientDependency),ServiceLifetime.Transient },
             { typeof(IScopedDependency),ServiceLifetime.Scoped },
             { typeof(ISingletonDependency),ServiceLifetime.Singleton },
             { typeof(IDependency),ServiceLifetime.Scoped },
         };

         //获取程序集所有实体模型Type
         var listTypes = GlobalAssemblies.GetTypes();
         
         foreach (var type in listTypes)
         {
             map.ToList().ForEach(aMap =>
             {
                 //依赖注入接口
                 var interfaceDependency = aMap.Key;
                 if (interfaceDependency.IsAssignableFrom(type) && interfaceDependency != type && !type.IsAbstract && type.IsClass)
                 {
                     //注入实现
                     Console.WriteLine("注入实现:" + type.FullName + ", " + aMap.Value.ToString());                        
                     services.Add(new ServiceDescriptor(type, type, aMap.Value));

                     //获取当前类的所有接口
                     var interfaces = listTypes.Where(x => x.IsInterface && x.IsAssignableFrom(type) && x != interfaceDependency).ToList();

                     //有接口,注入接口
                     if (interfaces.Count > 0)
                     {
                         interfaces.ForEach(@inteface =>
                         {
                             Console.WriteLine("注入接口:" + type.FullName + "," + @inteface.FullName + ", " + aMap.Value.ToString());
                             services.Add(new ServiceDescriptor(@inteface, type, aMap.Value));
                         });
                     }
                 }
             });
         };

         return services;
     }
 }

GlobalAssemblies 全局静态类

加载程序集Assembly。

作用:

  • 用于初始化CSFramework.EF组件(注册实体模型)
  • 用于获取所有接口和类,依赖注入服务

C#

    public static class GlobalAssemblies
    {
        /// <summary>
        /// 加载程序集Assembly。
        /// 作用:1.用于初始化CSFramework.EF组件(注册实体模型)
        ///      2.用于获取所有接口和类,依赖注入服务
        /// </summary>
        /// <param name="hostBuilder"></param>
        /// <returns></returns>
        public static void LoadAssemblies()
        {
            //加载以下程序集(包含所有实体模型、自定义服务的程序集)
            GlobalAssemblies.Assemblies = new List<System.Reflection.Assembly>
           {
                //如:CSFramework.LicenseServerCore.dll
                System.Reflection.Assembly.Load("CSFramework.LicenseServerCore"),
                System.Reflection.Assembly.Load("CSFramework.Models"),
           };
        }

        /// <summary>
        /// WebApi框架所有程序集
        /// </summary>
        public static List<System.Reflection.Assembly> Assemblies { get; set; }

        /// <summary>
        /// WebApi框架所有类型Types
        /// </summary>
        public static List<System.Type> GetTypes()
        {
            return Assemblies.SelectMany(m => m.GetExportedTypes()).ToList();
        }

    }

测试

相关推荐
Aimeast2 小时前
关于选择最佳.NET Core SSH服务器库的全面分析
c#·ssh
蒋劲豪3 小时前
WPF项目暴露WebApi接口;WinForm项目暴露WebApi接口;C#项目暴露WebApi接口;
开发语言·c#·wpf
code bean4 小时前
【C# 数据结构】队列 FIFO
开发语言·数据结构·c#
时光追逐者6 小时前
推荐几款开源免费的 .NET MAUI 组件库
microsoft·开源·c#·.net·.net core·maui
三天不学习8 小时前
.Net面试宝典【刷题系列】
面试·职场和发展·.net
JosieBook8 小时前
【.NET全栈】.NET包含的所有技术
.net
软件黑马王子8 小时前
C#初级教程(1)——C# 与.NET 框架:探索微软平台编程的强大组合
开发语言·c#
shepherd枸杞泡茶8 小时前
第3章 3.2 配置系统 .NET Core配置系统
后端·c#·asp.net·.net
让我们一起加油好吗9 小时前
【数学】数论干货(疑似密码学基础)
c语言·visualstudio·密码学
编程乐趣9 小时前
一文掌握DeepSeek本地部署+Page Assist浏览器插件+C#接口调用+局域网访问!全攻略来了!
开发语言·c#