Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

352
Views
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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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
    // ...

Kirk Woll's alternative via comment, more elegant in my opinion:

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!