精准掌握.NET依赖注入:DI自动注册服务轻松搞定
创始人
2025-07-14 08:11:15
0

概述:.NET依赖注入(DI)通过反射自动注册服务,示例展示了注册指定类、带特性类、项目下所有接口实现的类。简化配置,提高可维护性。

在.NET中,进行依赖注入(DI)的自动注册,可以通过反射机制和程序集扫描来实现。以下是详细的步骤以及相应的C#源代码示例,包括注册指定类、注册带有自定义特性的类、以及注册项目下所有带有接口实现的类(项目下的所有接口):

步骤1:创建接口和实现类

// 接口1
public interface IService1
{
    void PerformService1();
}

// 接口2
public interface IService2
{
    void PerformService2();
}

// 实现类1,实现IService1
public class MyService1 : IService1
{
    public void PerformService1()
    {
        Console.WriteLine("Service 1 performed.");
    }
}

// 实现类2,实现IService2
[CustomRegistration] // 带有自定义特性
public class MyService2 : IService2
{
    public void PerformService2()
    {
        Console.WriteLine("Service 2 performed.");
    }
}

// 实现类3,实现IService1和IService2
public class MyService3 : IService1, IService2
{
    public void PerformService1()
    {
        Console.WriteLine("Service 3 (Service 1 part) performed.");
    }

    public void PerformService2()
    {
        Console.WriteLine("Service 3 (Service 2 part) performed.");
    }
}

步骤2:创建自定义特性

// 自定义特性
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
sealed class CustomRegistrationAttribute : Attribute
{
}

步骤3:创建自动注册方法

using System;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;

class Program
{
    static void Main()
    {
        // 创建服务集合
        var services = new ServiceCollection();

        // 步骤4:注册指定类
        services.AddTransient();

        // 步骤5:注册带有自定义特性的类
        RegisterClassesWithAttribute(services);

        // 步骤6:注册项目下所有带有接口实现的类(项目下的所有接口)
        RegisterAllImplementationsOfInterfaces(services);

        // 构建服务提供程序
        var serviceProvider = services.BuildServiceProvider();

        // 步骤7:使用注册的服务
        var myService1 = serviceProvider.GetService();
        myService1.PerformService1();

        var myService2 = serviceProvider.GetService();
        myService2.PerformService2();

        var myService3 = serviceProvider.GetService();
        myService3.PerformService1();
        myService3.PerformService2();
    }

    // 自动注册带有指定特性的类
    static void RegisterClassesWithAttribute(IServiceCollection services)
        where TAttribute : Attribute
    {
        // 获取当前程序集
        var assembly = Assembly.GetExecutingAssembly();

        // 获取带有指定特性的所有类
        var attributedTypes = assembly.GetTypes()
            .Where(type => type.GetCustomAttributes(typeof(TAttribute), true).Any() && type.IsClass);

        // 注册这些类
        foreach (var attributedType in attributedTypes)
        {
            services.AddTransient(attributedType);
        }
    }

    // 自动注册项目下所有带有接口实现的类(项目下的所有接口)
    static void RegisterAllImplementationsOfInterfaces(IServiceCollection services)
    {
        // 获取当前程序集
        var assembly = Assembly.GetExecutingAssembly();

        // 获取项目下所有接口
        var interfaceTypes = assembly.GetTypes()
            .Where(type => type.IsInterface);

        // 获取实现了这些接口的所有类
        var implementationTypes = assembly.GetTypes()
            .Where(type => interfaceTypes.Any(interfaceType => interfaceType.IsAssignableFrom(type)) && type.IsClass);

        // 注册这些类
        foreach (var implementationType in implementationTypes)
        {
            services.AddTransient(implementationType);
        }
    }
}

在上述代码中:

  • 使用AddTransient方法注册了特定的MyService1类。
  • 使用RegisterClassesWithAttribute方法注册了带有CustomRegistrationAttribute特性的类。这里使用了反射机制来动态获取所有带有指定特性的类的类型,并将它们注册到DI容器中。
  • 使用RegisterAllImplementationsOfInterfaces方法注册了项目下所有实现接口的类。

请确保在项目中引用了Microsoft.Extensions.DependencyInjection相关的包。这是一个基本的示例,实际应用中可能需要更复杂的配置,具体取决于项目的需求。

相关内容

热门资讯

PHP新手之PHP入门 PHP是一种易于学习和使用的服务器端脚本语言。只需要很少的编程知识你就能使用PHP建立一个真正交互的...
网络中立的未来 网络中立性是什... 《牛津词典》中对“网络中立”的解释是“电信运营商应秉持的一种原则,即不考虑来源地提供所有内容和应用的...
各种千兆交换机的数据接口类型详... 千兆交换机有很多值得学习的地方,这里我们主要介绍各种千兆交换机的数据接口类型,作为局域网的主要连接设...
什么是大数据安全 什么是大数据... 在《为什么需要大数据安全分析》一文中,我们已经阐述了一个重要观点,即:安全要素信息呈现出大数据的特征...
如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
P2P的自白|我不生产内容,我... 现在一提起P2P,人们就会联想到正在被有关部门“围剿”的互联网理财服务。×租宝事件使得劳...
Intel将Moblin社区控... 本周二,非营利机构Linux基金会宣布,他们将担负起Moblin社区的管理工作,而这之前,Mobli...
施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
Windows恶意软件20年“... 在Windows的早期年代,病毒游走于系统之间,偶尔删除文件(但被删除的文件几乎都是可恢复的),并弹...