Search code examples
c#dependency-injectionblazor.net-5

Mixing Blazor Components, DI and C# 8 nullable


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.


Solution

  • Microsoft advice from Request a service in a component at ASP.NET Core Blazor dependency injection documentation:

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