C# , .netWebApi 实现类似Java 的Ioc 自动装配@Autowired

写C# 一直很羡慕Java的@Autowired 自动装配. 因为C# 必须手动在Ioc里注册,

例如

csharp 复制代码
builder.Services.AddSingleton<IHostedService, StartupInitializationService>();

但是我们也可以用C# 的反射机制 , 用接口实现自动装配. 写接口, 扩展方法如下:

csharp 复制代码
namespace MyFanucApi.Service.Ioc
{
    public interface IScoped
    {
    }
}
csharp 复制代码
namespace MyFanucApi.Service.Ioc
{
    public interface ISingleton
    {
    }
}
csharp 复制代码
namespace MyFanucApi.Service.Ioc
{
    public interface ITransient
    {
    }
}
csharp 复制代码
using System.Reflection;

namespace MyFanucApi.Service.Ioc
{
    public static class AutoRegister
    {
        public static IServiceCollection RegisterAllServices(this IServiceCollection services)
        {
            //获取当前程序集
            var entryAssembly = Assembly.GetEntryAssembly();

            //获取所有类型
            //!. null包容运算符,当你明确知道表达式的值不为null 使用!.(即null包容运算符)可以告知编译器这是预期行为,不应发出警告
            //例: entryAssembly!.GetReferencedAssemblies() 正常
            //entryAssembly.GetReferencedAssemblies() 编译器判断entryAssembly有可能为null,变量下方出现绿色波浪线警告

            var types = entryAssembly!.GetReferencedAssemblies()//获取当前程序集所引用的外部程序集
                .Select(Assembly.Load)//装载
                .Concat(new List<Assembly>() { entryAssembly })//与本程序集合并
                .SelectMany(x => x.GetTypes())//获取所有类
                .Distinct();//排重

            //三种生命周期分别注册
            Register<ITransient>(types, services.AddTransient, services.AddTransient);
            Register<IScoped>(types, services.AddScoped, services.AddScoped);
            Register<ISingleton>(types, services.AddSingleton, services.AddSingleton);

            return services;
        }

        /// <summary>
        /// 根据服务标记的生命周期interface,不同生命周期注册到容器里面
        /// </summary>
        /// <typeparam name="TLifetime">注册的生命周期</typeparam>
        /// <param name="types">集合类型</param>
        /// <param name="register">委托:成对注册</param>
        /// <param name="registerDirectly">委托:直接注册服务实现</param>
        private static void Register<TLifetime>(IEnumerable<Type> types, Func<Type, Type, IServiceCollection> register, Func<Type, IServiceCollection> registerDirectly)
        {
            //找到所有标记了Tlifetime生命周期接口的实现类
            var tImplements = types.Where(x => x.IsClass && !x.IsAbstract && x.GetInterfaces().Any(tinterface => tinterface == typeof(TLifetime)));

            //遍历,挨个以其他所有接口为key,当前实现为value注册到容器中
            foreach (var t in tImplements)
            {
                //获取除生命周期接口外的所有其他接口
                var interfaces = t.GetInterfaces().Where(x => x != typeof(TLifetime));
                if (interfaces.Any())
                {
                    foreach (var i in interfaces)
                    {
                        register(i, t);
                    }
                }

                //有时需要直接注入实现类本身
                registerDirectly(t);
            }
        }

    }
}

在Ioc中注册:

csharp 复制代码
//自动注入
builder.Services.RegisterAllServices();

这样, 凡是实现接口IScoped , ISingleton 的类都在Ioc中自动注册了

相关推荐
ajassi20001 分钟前
开源 java android app 开发(十八)最新编译器Android Studio 2025.1.3.7
android·java·开源
纤瘦的鲸鱼5 分钟前
Spring Gateway 全面解析:从入门到进阶实践
java·spring·gateway
用户32941900421619 分钟前
Java接入DeepSeek实现流式、联网、知识库以及多轮问答
java
Knight_AL23 分钟前
浅拷贝与深拷贝详解:概念、代码示例与后端应用场景
android·java·开发语言
DolphinScheduler社区25 分钟前
# 3.1.8<3.2.0<3.3.1,Apache DolphinScheduler集群升级避坑指南
java·大数据·开源·apache·任务调度·海豚调度
Le1Yu1 小时前
黑马商城微服务项目准备工作并了解什么是微服务、SpringCloud
java·微服务·架构
ZhengEnCi1 小时前
🚀创建第一个 SpringBoot 应用-零基础体验开箱即用的神奇魅力
java·spring boot
宠友信息1 小时前
仿小红书短视频APP源码:Java微服务版支持小程序编译的技术解析
java·微服务·音视频
技术支持者python,php1 小时前
winform本地上位机-ModbusRTC1.上位机控制台与数据监控(数据监控架构思维与图表系列)
c#
努力努力再努力wz1 小时前
【C++进阶系列】:万字详解智能指针(附模拟实现的源码)
java·linux·c语言·开发语言·数据结构·c++·python