.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();
        }

    }

测试

相关推荐
Dm_dotnet2 小时前
Stylet启动机制详解:从Bootstrap到View显示
c#
三千道应用题4 小时前
WPF&C#超市管理系统(6)订单详情、顾客注册、商品销售排行查询和库存提示、LiveChat报表
开发语言·c#·wpf
唐青枫8 小时前
别滥用 Task.Run:C# 异步并发实操指南
c#·.net
我好喜欢你~15 小时前
C#---StopWatch类
开发语言·c#
一阵没来由的风19 小时前
拒绝造轮子(C#篇)ZLG CAN卡驱动封装应用
c#·can·封装·zlg·基础封装·轮子
zzzhpzhpzzz1 天前
Win10快速安装.NET3.5
.net·win10
许泽宇的技术分享1 天前
Windows MCP.Net:基于.NET的Windows桌面自动化MCP服务器深度解析
windows·自动化·.net
一枚小小程序员哈1 天前
基于微信小程序的家教服务平台的设计与实现/基于asp.net/c#的家教服务平台/基于asp.net/c#的家教管理系统
后端·c#·asp.net
Eternity_GQM1 天前
【Word VBA Zotero 引用宏错误分析与改正指南】【解决[21–23]参考文献格式插入超链接问题】
开发语言·c#·word
cimeo1 天前
【C 学习】06-算法&程序设计举例
c#