Search code examples
c#design-patternsdependency-injectionblazor

Is there a difference between the three dependency injection syntaxes in Blazor (.net 7)?


As far as I can tell, all three of these patterns work to inject a DI service in a Blazor (.net 7/C#/Razor) project:

  1. @inject NavigationManager NavManager in the Razor component
  2. [Inject] private NavigationManager NavManager { get; set; } in the class definiton
  3. The typical DI pattern:
   private readonly IMyDependency _myDependency;
   public Index2Model(IMyDependency myDependency)
   {
       _myDependency = myDependency;            
   }

As far as I can tell, they all work.

Is there any difference in their implementation? Is it safe to use any or all of them?

Thanks!


Solution

  • Additional Information to Dimitris's answer.

    Yes there is a difference between 1/2 and 3. A component's injection process (handled by the Renderer process) is run after the Ctor. You can't use any DI services in the Ctor.

    The difference between 1 and 2 is nullability.

    1. With @inject, the Razor compiler disables nullable checking for the property.
    2. With [Inject], you need to handle it manually. The normal way to do this is to set default! as the default value. It will never be null once you get to SetParametersAsync and the normal lifecycle methods as the runtime will throw an exception during the injection process if it can't find the service.
    [Inject] private NavigationManager NavManager { get; set; } = default!;