Dorian
Dorian

Reputation: 983

blazor dependency injection difference in .razor than in code behind .cs

can someone please explain to me

why with

  @inject ILogger<Counter> logger

we have

enter image description here

and with

 [Inject] ILogger<Counter> logger { get ; set; }

we have

enter image description here

??? same DI system and diferent implementations ? i does no want to add nullcheck when i do this from code ? thanks and regards

Upvotes: 2

Views: 1431

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273179

When you look at the generated code, Blazor just adds a #nullable disable line:

@inject ILogger<Counter> logger

becomes

#nullable disable
[InjectAttribute] private ILogger<Counter> logger { get; set; }

But I wouldn't want that in my own code, so indeed the best practice is:

[Inject] ILogger<Counter> logger { get ; set; } = default!;

Upvotes: 4

gunr2171
gunr2171

Reputation: 17510

The razor syntax is smart enough to know that when you @inject a service, it MUST be resolved. You cannot end up with a null variable - you would get an exception instead. That's why you don't need a null check in razor.

When you're using code behind files with properties, even though you add the [Inject] attribute, the C# compiler isn't smart enough to know that simply adding the attribute guarantees that the property won't contain a null value. The compiler doesn't know where the property will be assigned from, or even if it will be assigned.

The easy solution is to say "yes compiler, I know what I'm doing".

[Inject] ILogger<Counter> logger { get; set; } = default!;

Upvotes: 1

Related Questions