1

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

d00lar
  • 802
  • 7
  • 25

2 Answers2

3

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!;
H H
  • 263,252
  • 30
  • 330
  • 514
  • and what is recomended solution for custom my services? lets say i vave UserService so if i do ` UserService us { get; set; } = default ! ` it yells at me that there is no target for default ? – d00lar Jul 27 '22 at 13:03
  • A custom service should be no different from a standard one. So that error is from something else. – H H Jul 27 '22 at 14:42
1

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!;
gunr2171
  • 16,104
  • 25
  • 61
  • 88
  • Thanks But in my opinion M$ devs should work this out. It should be identical and inject attribute should solve this itself. – d00lar Jul 26 '22 at 14:30
  • 1
    The C# code that is generated from razor is pretty much identical. It also uses an `InjectAttribute` behind the scenes. However, it also disables the nullable context by inserting `#nullable disable`, which is why you don't see a warning. If you declare the property in your code-behind, it is up to you to handle this warning in whatever way you deem appropriate, since it is your code. – lrpe Jul 26 '22 at 14:51