C#ASP.NET Core [Inject]依赖关系注入的属性用法 [英] C# ASP.NET Core [Inject] Attribute Usage for Dependency Injection
问题描述
我一直在内部构造函数中使用依赖注入,这种构造一直很好.我最近了解了[Inject]属性,但似乎无法使其正常工作.也许它不兼容,或者我滥用它.
I have been using dependency injection inside a constructor which has been working great. I have recently learned of the [Inject] attribute, but cannot seem to get it to work. Maybe it's not compatible or perhaps I am misusing it.
在Startup.cs中将其注册为服务:
Registering it as a service in Startup.cs:
services.AddScoped<IUserProfileService, UserProfileService>();
将其用作具有[Inject]属性的属性:
Using it as a property with the [Inject] attribute:
[Microsoft.AspNetCore.Components.Inject]
private IUserProfileService _UserProfileService { get; set; }
调用_UserProfileService时,它尚未初始化,并且仍然为null.如果我切换回注入到构造函数中,它将起作用.我是滥用该属性还是完全不可能?
When _UserProfileService is called upon, it has not been initialized and is still null. If I switch back to injecting it in the constructor, it works. Am I misusing the attribute or is it simply not possible?
使用Blazor的ASP.Net Core 3.1
ASP.Net Core 3.1, using Blazor
推荐答案
[Inject]
属性仅应用于Blazor组件.即使使用 [Inject]
标记了这些属性,属性注入也不会应用于对 IServiceCollection
进行的注册.内置的DI容器无法应用属性注入.
The [Inject]
attribute is solely applied to Blazor Components. Property injection will not be applied to registrations made to the IServiceCollection
, even if you mark those properties with [Inject]
. The built-in DI Container is not capable of applying property injection.
存在 InjectAttribute
的唯一原因是在Razor页面中使用 @inject
标记.当您使用 @inject
标记时,Blazor将在Blazor组件上生成一个公共属性,该公共属性标记为 [Inject]
.
The sole reason for the existence of the InjectAttribute
is to use the @inject
tag in Razor pages. When you use the @inject
tag, Blazor will generate a public property on your Blazor Component that is marked with [Inject]
.
尽管属性注入是 DIPP& P (第4.4节),该书还警告了属性注入"的缺点以及作者(Mark Seemann和I)指出:
Although Property Injection is described as a valid pattern for practicing DI in DIPP&P (section 4.4), the book also warns about the downsides of Property Injection, and the authors (Mark Seemann and I) state that:
在构建应用程序[...]时,我们永远不会使用属性注入,因此您应谨慎使用.即使您可能具有依赖项的 Local Default ,构造函数注入仍然为您提供了更好的选择.构造函数注入更简单,更可靠.您可能会认为您需要属性注入来解决循环依赖关系,但这是代码的味道,我们将在第6章中进行解释.
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.
因此,在任何可能的情况下,请避免使用属性注入,而应使用构造函数注入作为向使用者提供依赖项的唯一方法.
So, whenever possible, refrain from using Property Injection and use Constructor Injection as your sole way to provide dependencies to a consumer.
这篇关于C#ASP.NET Core [Inject]依赖关系注入的属性用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!