惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
雷峰网
雷峰网
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
B
Blog
Y
Y Combinator Blog
WordPress大学
WordPress大学
Microsoft Azure Blog
Microsoft Azure Blog
小众软件
小众软件
G
Google Developers Blog
云风的 BLOG
云风的 BLOG
罗磊的独立博客
博客园 - 三生石上(FineUI控件)
博客园 - 叶小钗
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
量子位
The Cloudflare Blog
T
The Blog of Author Tim Ferriss
博客园_首页
B
Blog RSS Feed
Hugging Face - Blog
Hugging Face - Blog
IT之家
IT之家
阮一峰的网络日志
阮一峰的网络日志
L
LangChain Blog
宝玉的分享
宝玉的分享

博客园 - 我有我奥妙

【BenchmarkDotNet】测试多方式的对象映射 【排名】处理同分数的排名 【Quartz】.Net8使用定时任务 【模型验证】未被异常捕获到 【Ant Design Vue】相关 【根节点】C#找树形数据的根节点Id 【C#】枚举值 【ECharts】图表自定义显示标题 【消息队列】介绍 【Nginx】Windows部署Vue 设计模式(一)-介绍 【.NetCore】创建本机的静态文件服务器 NLog(一)-使用示例 【nssm】windows上netcore注册为服务 【字符串排序】C#和前端js排序问题 【长路经】C#读取文件抛出FileNotFoundException异常 【RestSharp】常用的几个请求方式 【笔记软件】Obsidian的使用 【浏览器扩展】编写Firefox和Chrome的扩展程序
【自动注入】.NET8/.NETCore 依赖注入:自动注入项目中所有接...
我有我奥妙 · 2025-04-21 · via 博客园 - 我有我奥妙

参考

https://blog.csdn.net/jonnysun/article/details/144201359

创建工具类库

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" />
  </ItemGroup>

</Project>

IDependency接口

    public interface IDependency { }

    public interface ITransientDependency : IDependency { }

    public interface IScopedDependency : IDependency { }

    public interface ISingletonDependency : IDependency { }

全局程序集

    public static class GlobalAssemblies
    {
        public static readonly Assembly[] AllAssemblies =
        [
            Assembly.Load("Keep.Application"),
        ];

        public static readonly Type[] AllTypes = [.. AllAssemblies.SelectMany(x => x.GetTypes())];
    }

HostExtensions扩展方法

    public static class HostExtensions
    {
        public static IServiceCollection AddInjectionServices(this IServiceCollection services)
        {
            Dictionary<Type, ServiceLifetime> lifeTimeMap = new()
            {
                 { typeof(ITransientDependency),ServiceLifetime.Transient },
                 { typeof(IScopedDependency),ServiceLifetime.Scoped },
                 { typeof(ISingletonDependency),ServiceLifetime.Singleton },
                 { typeof(IDependency),ServiceLifetime.Scoped },
             };

            var typeList = GlobalAssemblies.AllTypes;

            foreach (var type in typeList)
            {
                foreach (var map in lifeTimeMap)
                {
                    var interfaceDependency = map.Key;
                    if ((interfaceDependency.IsAssignableFrom(type) && interfaceDependency != type && !type.IsAbstract && type.IsClass) == false)
                        continue;

                    bool hasInterafce = false;
                    foreach (var @inteface in typeList.Where(x => x.IsInterface && x.IsAssignableFrom(type) && x != interfaceDependency))
                    {
                        services.Add(new ServiceDescriptor(@inteface, type, map.Value));
                        hasInterafce = true;
                    }

                    if (hasInterafce == false)
                        services.Add(new ServiceDescriptor(type, type, map.Value));
                }
            }

            return services;
        }
    }

使用Program.cs

builder.Services.AddInjectionServices();