Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

351
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda