I am using .net 5 for a Blazor app in a project with nullable enabled. It is using Code Behind to create Blazor Components. I want to use a constructor so that I can avoid marking every non DI property as nullable to simplify accessing them in my blazor code. However, If I create a constructor like
public PageNumberOne(ILogger<PrimaryItem> logger) {}
I get the error MissingMethodException: No parameterless constructor defined for type
If I use the inject attribute on the DI items then I have the warning - Non-nullable property _logger must contain a non-null value when exciting the constructor
So how do I mix DI with nullable without just marking every property as nullable?
I could also create them in the main body of the "code" block but then I cannot access my DI items for initialization because they are not available until the OnInitialized. So again I have to mark them as Nullable.
I work in the same scenario: Blazor Components + Nullable. What I do is to declare parameters as nullable and I use ! (null-forgiving) operator when I use the parameters:
[Inject]
public NavigationManager? MyNavigationManager {get; set;}
[Parameter]
public MenuItem? MyMenuItem {get; set;}
protected void Foo()
{
var currenturi = MyNavigationManager!.Uri; //<--- here
var sometext = MyMenuItem!.text; //<--- here
// ...
Alternatively, just assume injection will work and declare the property like:
[Inject]
public NavigationManager MyNavigationManager {get; set;} = default!;
I have tested it and works fine with interfaces or classes without parameterless constructor.