混合 Blazor 组件、DI 和 C# 8 可为空

Mixing Blazor Components, DI and C# 8 nullable

我在启用了可为空的项目中将 .net 5 用于 Blazor 应用程序。它使用代码隐藏来创建 Blazor 组件。我想使用一个构造函数,这样我就可以避免将每个非 DI 属性 标记为可为空,以简化在我的 blazor 代码中访问它们的过程。但是,如果我创建一个构造函数 public PageNumberOne(ILogger<PrimaryItem> logger) {}

我收到错误 MissingMethodException: 没有为类型定义无参数构造函数

如果我在 DI 项上使用 inject 属性,那么我会收到警告 - Non-nullable 属性 _logger must contain a non-null value when exciting the constructor

那么,如何将 DI 与可为 nullable 混合使用,而不仅仅是将每个 属性 标记为可为 nullable?

我也可以在“代码”块的主体中​​创建它们,但是我无法访问我的 DI 项进行初始化,因为它们在 OnInitialized 之前不可用。所以我必须再次将它们标记为 Nullable。

Request a service in a component 在 ASP.NET 核心 Blazor 依赖项注入文档中的 Microsoft 建议:

Since injected services are expected to be available, don't mark injected services as nullable. Instead, assign a default literal with the null-forgiving operator (default!).

[Inject]
private IExampleService ExampleService { get; set; } = default!;