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.