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

推荐订阅源

钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
G
Google Developers Blog
小众软件
小众软件
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 【当耐特】
爱范儿
爱范儿
博客园 - 聂微东
美团技术团队
大猫的无限游戏
大猫的无限游戏
The Cloudflare Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
有赞技术团队
有赞技术团队
云风的 BLOG
云风的 BLOG
罗磊的独立博客
V
Visual Studio Blog
WordPress大学
WordPress大学
Stack Overflow Blog
Stack Overflow Blog
雷峰网
雷峰网
人人都是产品经理
人人都是产品经理
Blog — PlanetScale
Blog — PlanetScale
V
V2EX
The GitHub Blog
The GitHub Blog
Apple Machine Learning Research
Apple Machine Learning Research
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报

博客园 - 生命体验之kevin-Y

windbg内存占用分析常用命令 如何让Trae IDE调用windbg来分析dump文件 Avalonia.Controls.DataGrid自动合并列 asp.net core如何实现Controller热更新 windbg无法分析dotnetframework3.5的dmp vscode指定python文件的执行程序 golang离线开发-windows-vscode go语言学习 - caddy配置的一些发现 go语言学习 - caddy添加nacos-gateway 学习jsp-使用IDEA2024社区版 ravendb源代码学习一:服务启动 修整程序集需要 .NET Core 3.0 或更高版本。 打开电脑后一直弹出“交互式检测服务”窗口 Idea2024-java-Maven开发配置 C#获取事件绑定的方法 java.util.zip.DataFormatException: incorrect header check Build Secure Web Services With SOAP Headers and Extensions “System.Net.Http.HttpContent”不包含“ReadAsAsync”的定义 C#入门:如何合理制定方法参数-下 C#入门:如何合理制定方法参数-上 拷贝对象的开源工具类-FastMapper-TinyMapper-Mapster
asp.net core通过配置决定AddSingleton的实现类
生命体验之kevin-Y · 2025-09-30 · via 博客园 - 生命体验之kevin-Y

有一些接口,我们也不知道最终谁来实现, 又或者不同的环境有不同的实现。于是我们希望通过配置来处理。

//通过配置决定实际注入类
builder.Services.AddSingletonIfCfg<ISmsVerifyCodeService>(builder.Configuration, "SmsVerifyCodeService:TypeName");

那我们只需在appsetting.json中修改,以使用不同实现。下面注入的是:SmsAdapter.AliyunSMSVerifyCodeService, SmsAdapter

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "SmsVerifyCodeService": {
    "TypeName": "SmsAdapter.AliyunSMSVerifyCodeService, SmsAdapter",
    "Aliyun": {"AccessId": "yyyyyy",
      "AccessSecret": "bbbb",      
      "SignName": "myapp",
      "TemplateCode": "SMS_222"
    }    
  }
}
具体的AddSingletonIfCfg方法在以下静态工具类提供
public static class DynamicServiceFactory
{
    public static void AddSingletonIfCfg<T>(this IServiceCollection services, IConfiguration config, string configKey)
    {
        var typeName = config.GetValue<string>(configKey);
        if (string.IsNullOrEmpty(typeName))
        {
            Console.WriteLine($" AddSingletonIfCfg miss configKey: {configKey} .");
            return;
        }

        var type = Type.GetType(typeName);
        if (type == null)
            throw new Exception($" AddSingletonIfCfg miss typeName: {typeName} .");
        if (!typeof(T).IsAssignableFrom(type))
            throw new Exception($" AddSingletonIfCfg typeName: {typeName} not implement {typeof(T).FullName} .");
        // 使用ActivatorUtilities创建实例并注册服务
        services.AddSingleton(typeof(T), serviceProvider =>
        {
            try
            {
                return ActivatorUtilities.CreateInstance(serviceProvider, type);
            }
            catch (Exception ex)
            {
                throw new Exception($"Failed to create instance of type {typeName}.", ex);
            }
        });
    }
}

好了,我们就可以增加一个类库项目SmsAdapter,一个类AliyunSMSVerifyCodeService来实现ISmsVerifyCodeService。

AliyunSMSVerifyCodeService类可以象在主程序中一样书写,可以使用注入的所有服务。

另外,一般来说ISmsVerifyCodeService定义在基础类库,就是asp.net core主程序和SmsAdapter项目都会引用的项目。而主程序和SmsAdapter项目可以说没有多大关联,都可以不知道对方的存在。