Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ASP.NET Core [Inject] Attribute Usage for Dependency Injection

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.

Registering it as a service in Startup.cs:

services.AddScoped<IUserProfileService, UserProfileService>();

Using it as a property with the [Inject] attribute:

[Microsoft.AspNetCore.Components.Inject]
private IUserProfileService _UserProfileService { get; set; }

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?

ASP.Net Core 3.1, using Blazor

like image 839
Izacch Avatar asked Mar 08 '26 20:03

Izacch


1 Answers

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.

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].

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:

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.

like image 75
Steven Avatar answered Mar 11 '26 10:03

Steven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!