ASP.NET中[Inject]属性注入失效,构造注入正常的原因?
问题描述
我有两个服务:TransactionService和TestService,分别实现接口ITransactionService和ITestService。TransactionService需要调用TestService,尝试通过依赖注入实现:
在Program.cs中配置:
builder.Services.AddScoped<ITestService, TestService>();
第一种属性注入方式的TransactionService代码:
namespace Accounting.Web.Services { public class TransactionService : ITransactionService { [Inject] private ITestService TestService { get; set; } public async void LoadTransactions(int Year, int Month) { _testService.Test(); } } }
运行时抛出空引用异常:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at Accounting.Web.Services.TransactionService.LoadTransactions(Int32 Year, Int32 Month) in E:\aspnet\Accounting.Web\Services\TransactionService.cs:line 24 at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__128_1(Object state) at System.Threading.QueueUserWorkItemCallbackDefaultContext.Execute() at System.Threading.ThreadPoolWorkQueue.Dispatch() at System.Threading.ThreadPool.Callback() ThreadPool Callback threw an unhandled exception of type System.NullReferenceException
改用构造注入后代码正常运行:
namespace Accounting.Web.Services { public class TransactionService : ITransactionService { private ITestService _testService; public TransactionService(ITestService testService) { _testService = testService; } public async void LoadTransactions(int Year, int Month) { _testService.Test(); } } }
请问为何第一种属性注入方式无效?或者需要配置什么才能让它生效?
原因及解决方案
原生DI不支持属性注入
.NET内置的依赖注入容器只原生支持构造注入,不会自动识别并注入带有[Inject]属性的成员。你用到的[Inject]属性是Blazor框架特有的,仅在Blazor组件中会被框架处理,普通服务类里无法生效。实现属性注入的可选方案
若一定要用属性注入,有两种途径:- 使用第三方DI容器:比如Autofac、Ninject、SimpleInjector等,这些容器原生支持属性注入,只需按照对应容器的配置规则启用即可。
- 自定义服务激活逻辑:通过实现
IServiceProvider或利用ActivatorUtilities扩展,在服务实例创建后手动扫描并注入带有特定属性的成员,但这种方式复杂度较高,常规场景不推荐。
构造注入的优势
构造注入是.NET官方推荐的依赖注入方式,能确保服务在创建时就完成所有依赖初始化,从根源避免空引用异常,同时让依赖关系更清晰,便于测试和维护。
内容的提问来源于stack exchange,提问作者Musaffar Patel
相关产品推荐
相关产品推荐

