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

    }

测试

相关推荐
喵叔哟1 小时前
16.【.NET 8 实战--孢子记账--从单体到微服务--转向微服务】--微服务基础工具与技术--Github Action
微服务·github·.net
BruceNeter2 小时前
C# 使用StackExchange.Redis实现分布式锁的两种方式
redis·c#
白熊1884 小时前
【计算机视觉】CV实战项目 -深度解析PaddleSegSharp:基于PaddleSeg的.NET图像分割解决方案
人工智能·计算机视觉·.net
互联网打工人no15 小时前
.NET8 依赖注入组件
开发语言·c#·.net·ioc
程序设计实验室12 小时前
一次小而美的重构:使用 C# 在 Avalonia 中生成真正好看的词云
c#
电商api接口开发13 小时前
ASP.NET MVC 入门指南二
前端·c#·html·mvc
HelloRevit16 小时前
.NET 10 中的新增功能
.net
o0向阳而生0o16 小时前
28、.NET 中元数据是什么?
microsoft·c#·.net
niuTaylor17 小时前
Linux驱动开发快速上手指南:从理论到实战
linux·运维·开发语言·驱动开发·c#
军训猫猫头18 小时前
89.WPF 中实现便捷的数字输入框:DecimalUpDown 控件的使用 WPF例子 C#例子.
开发语言·c#·wpf