当前位置: 首页 > news >正文

.Net 中的 ActivatorUtilitiesConstructor 特性

.Net 中的 ActivatorUtilitiesConstructor 特性

[ActivatorUtilitiesConstructor]是 .NET 依赖注入中的一个特性,用于指导 Microsoft.Extensions.DependencyInjection(MSDI)在类型有多个构造函数时,选择哪个构造函数进行实例化。

主要用途

1.解决构造函数选择歧义

当一个类有多个构造函数时,MSDI 默认选择参数最多且都能从容器中解析的构造函数。但有时这会导致问题:

publicclassMyService{// 默认情况下,DI 会选择这个构造函数(参数最多)publicMyService(IService1s1,IService2s2,stringconfigValue){// configValue 无法从容器解析,会抛出异常!}// 实际上我们想用这个publicMyService(IService1s1,IService2s2){// 只有可解析的参数}}

2.明确指定构造函数

使用[ActivatorUtilitiesConstructor]明确告诉 DI 使用哪个:

publicclassMyService{publicMyService(IService1s1,IService2s2,stringconfigValue){// 这个不会被 DI 使用}[ActivatorUtilitiesConstructor]publicMyService(IService1s1,IService2s2){// DI 会优先使用这个构造函数}}

工作原理

  1. 标记优先级:标记的构造函数会被优先考虑
  2. 兼容性检查:只考虑标记的构造函数能否从容器解析所有参数
  3. 回退机制:如果标记的构造函数参数无法全部解析,会尝试其他构造函数

常见场景

场景1:有可选参数时

publicclassReportService{privatereadonlyILogger_logger;privatereadonlystring_format;publicReportService(ILogger<ReportService>logger){_logger=logger;_format="Default";}[ActivatorUtilitiesConstructor]publicReportService(ILogger<ReportService>logger,IOptions<ReportOptions>options){_logger=logger;_format=options.Value.Format;}}

场景2:第三方库扩展

// 扩展第三方库的类publicclassExtendedThirdPartyService:ThirdPartyService{// 第三方库可能没有无参构造函数publicExtendedThirdPartyService():base("default"){}[ActivatorUtilitiesConstructor]publicExtendedThirdPartyService(IConfigurationconfig):base(config.GetValue<string>("ApiKey")){}}

使用注意事项

1.仅用于ActivatorUtilities.CreateInstance

// 这个特性主要影响以下方法:varinstance=ActivatorUtilities.CreateInstance<MyService>(serviceProvider);varinstance=ActivatorUtilities.CreateInstance(serviceProvider,typeof(MyService));

2.与直接容器解析的区别

// 使用特性 - 受 [ActivatorUtilitiesConstructor] 影响services.AddTransient<MyService>();varservice=serviceProvider.GetService<MyService>();// 直接注册实例工厂 - 不使用该特性services.AddTransient(sp=>newMyService("hardcoded"));

3.多个标记会报错

publicclassBadExample{[ActivatorUtilitiesConstructor]publicBadExample(IService1s1){}[ActivatorUtilitiesConstructor]// ❌ 运行时错误:多个标记publicBadExample(IService2s2){}}

实际示例

publicclassPaymentProcessor{privatereadonlyIPaymentGateway_gateway;privatereadonlybool_useSandbox;// 用于测试或特定场景publicPaymentProcessor(IPaymentGatewaygateway){_gateway=gateway;_useSandbox=false;}// 生产环境使用 - 从配置读取[ActivatorUtilitiesConstructor]publicPaymentProcessor(IPaymentGatewaygateway,IConfigurationconfig){_gateway=gateway;_useSandbox=config.GetValue<bool>("Payment:UseSandbox");}}// 注册services.AddScoped<IPaymentGateway,StripeGateway>();services.AddScoped<PaymentProcessor>();// 使用时,DI 会自动选择带 [ActivatorUtilitiesConstructor] 的构造函数

替代方案

如果不想使用特性,也可以:

  1. 使用工厂方法注册
services.AddScoped(sp=>newMyService(sp.GetRequiredService<IService1>(),sp.GetRequiredService<IService2>()));
  1. 简化设计(推荐):尽量保持单个构造函数,使用 Options 模式处理配置。

总结

[ActivatorUtilitiesConstructor]是一个解决构造函数选择问题的工具,但在良好设计的应用中应该很少需要。优先考虑通过单一构造函数Options 模式来简化设计,这会使代码更清晰且易于测试。

http://www.jsqmd.com/news/250199/

相关文章:

  • 学霸同款2026 TOP8 AI论文软件:本科生毕业论文必备测评
  • django-flask基于python的大学生公益活动志愿服务系统的设计与实现
  • django-flask基于python的大学生兼职网站的设计与实现
  • Open Code教程(四)| 高级配置与集成
  • 软件打开提示找不到d3dx9_30.dll文件 如何修复? 附免费下载方法
  • Open Code教程(一)| 快速入门:安装配置与基础使用
  • django-flask基于python的大学生班级档案管理系统
  • 救命神器10个一键生成论文工具,专科生毕业论文轻松搞定!
  • 【实测有效】分享5款亲测好用的论文降AI神器,轻松解决AI率过高问题,通过AI检测
  • django-flask基于python的大学生创新计划项目管理web系统
  • 学霸同款9个AI论文软件,本科生轻松搞定毕业论文!
  • 论文AI率过高怎么办?亲测推荐5款降AI神器,高效降AIGC看这篇就够了!【建议收藏】
  • 毕业生必看:如何应对越来越严的AI检测?5款专业降AI工具实测分享,教你有效降低ai率。
  • Windows系统更新常出错?一键永久彻底禁止Windows系统自动更新,简单易用,小白也可轻松操作附工具
  • Windows Server 2016 中文版、英文版下载 (2026 年 1 月更新)
  • 选择敏捷咨询公司前,你一定要问的几个问题
  • 免费与付费降AI工具怎么选?对比5款lunwen 降ai主流产品,哪款才是真正的降AI率神器
  • 吐血推荐专科生必用AI论文平台TOP9:开题报告文献综述全搞定
  • Windows最强”播放器?PotPlayer播放器|友友们都在用的视频播放器
  • 高性能32位MCU微控制器数字电源参考方案
  • gru 记忆是记当前episode的内容吗
  • django基于python的农村医疗健康管理系统的设计与实现
  • ✅ Spring/SpringBoot 定时任务 完整版超详细教程(零基础必会,直接能用)@Scheduled 与 SchedulingConfigurer
  • 字节跳动 Coze(扣子)万字长文:从“会聊天”到“能交付”的 AI 智能体平台全景解析
  • 同轴投影机和偏轴投影机的区别
  • BMP280气压传感器原理图设计,已量产(压力传感器)
  • 用SQL实现三次指数平滑预测:递归与非递归两种解法详解
  • 槽型光电开关传感器原理图设计,已量产(光电传感器)
  • 全网最全本科生必用TOP10 AI论文网站测评
  • django基于python的旅游个性化定制平台的设计与实现