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:
@inject NavigationManager NavManager
in the Razor component[Inject] private NavigationManager NavManager { get; set; }
in the class definiton 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!
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.
@inject
, the Razor compiler disables nullable checking for the property.[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!;