Search code examples
dependency-injectionblazorblazor-client-side

Blazor client side [inject] properties always return null


In razor pages I'm using @inject Blazored.LocalStorage.ISyncLocalStorageService localStorage and it's working fine. But from non-razor connected classes (services and helpers) using

[Inject]
protected Blazored.LocalStorage.ISyncLocalStorageService localStorage { get; set; }

Always returns null. Is there something additional that is needed to get DI to work in non-Razor files? Or do I have to push all of the DI through Constructors all the way down from the UI layer?


Solution

  • The following is based only on my own experience, so I might be proved wrong...

    Only constructor injection works in non-razor objects. Thus you cannot define a property annotated with the Inject attribute and expect it to be populated with an instance of a given object. Use constructor injection instead.

    With Razor objects, however, you can use the @inject directive to inject services into Razor components, but you can also use the Inject attribute with properties in razor component class definition (.razor.cs ) and in @code blocks ( .razor ).

    Hope this helps...