简体   繁体   中英

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

在此处输入图像描述

and with

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

we have

在此处输入图像描述

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

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!;

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!;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM