我一直在一个运行良好的构造函数中使用依赖注入(inject)。我最近了解了 [Inject] 属性,但似乎无法让它工作。也许它不兼容,或者我滥用了它。
在 Startup.cs 中将其注册为服务:
services.AddScoped<IUserProfileService, UserProfileService>();
将其用作具有 [Inject] 属性的属性:
[Microsoft.AspNetCore.Components.Inject]
private IUserProfileService _UserProfileService { get; set; }
当 _UserProfileService 被调用时,它还没有被初始化并且仍然为空。如果我切换回在构造函数中注入(inject)它,它会起作用。我是在滥用属性还是根本不可能?
ASP.Net Core 3.1,使用 Blazor
最佳答案
[Inject]
属性仅适用于 Blazor 组件。属性注入(inject)不会应用于对 IServiceCollection
的注册,即使您使用 [Inject]
标记这些属性。内置 DI Container 无法应用属性注入(inject)。
InjectAttribute
存在的唯一原因是在 Razor 页面中使用 @inject
标记。当您使用 @inject
标记时,Blazor 将在您的 Blazor 组件上生成一个公共(public)属性,该属性标有 [Inject]
。
虽然Property Injection是 described as a valid pattern在 DIPP&P 中练习 DI (第 4.4 节),该书还警告了 Property Injection 的缺点,作者(Mark Seemann 和我)指出:
When building applications [...] we never use Property Injection, and you should do so sparingly. Even though you might have a Local Default for a Dependency, Constructor Injection still provides you with a better alternative. Constructor Injection is simpler and more robust. You might think you need Property Injection to work around a cyclic Dependency, but that’s a code smell, as we’ll explain in chapter 6.
因此,尽可能避免使用属性注入(inject),而是使用构造函数注入(inject)作为向消费者提供依赖项的唯一方式。
关于C# ASP.NET Core [Inject] 依赖注入(inject)的属性用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65629065/