C# ASP.NET Core [Inject] 依赖注入(inject)的属性用法

标签 c# asp.net-core dependency-injection

我一直在一个运行良好的构造函数中使用依赖注入(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 Injectiondescribed as a valid patternDIPP&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/

相关文章:

c# - WPF 中 OnInitialized 和 OnSourceInitialized 的区别

c# - "i"在此 LINQ 语句中的何处获取其值?

c# - .net core 3依赖注入(inject)服务作为参数 'configure'

c# - 在 ASP.NET MVC Controller 中使用临时私有(private)变量

c# - 如何在 .Net Core 3 中引用托管服务?

c# - SignalR 集线器客户端在触发事件时为空

ios - 使用 Storyboard时如何对第一个屏幕的 View Controller 进行依赖注入(inject)?

c# - Unity MVC 默认解析类型吗?

java - 依赖注入(inject) : How to maintain multiple configurations?

javascript - 运行 javascript 按钮 C#