Search code examples
dependency-injectionblazorblazor-client-side

Blazor WebAssembly: using Constructor injection for injecting Blazored.LocalStorage into a service


The package Blazored.LocalStorage is:

a library to provide access to local storage in Blazor applications

Injecting the service into a component is easy:

@inject Blazored.LocalStorage.ILocalStorageService localStorage

and if we want to inject it into the code behind:

[Inject]
private ILocalStorageService localStorage { get; set; }

But suppose I want to inject it into another service (let say for centralizing the control):

public class StorageManagement
{
    public StorageManagement(LocalStorageService localStorage)
    {
        //How to initialize it here?
    }
}

I do not know how to initialize an instance of the service in the constructor of StorageManagement and also how to set the parameters of constructor of StorageManagement in Program.cs :

builder.Services.AddSingleton(e => new StorageManagement(//?));

Solution

  • Just builder.Services.AddBlazoredLocalStorage(); or builder.Services.AddBlazoredLocalStorage(config => config.JsonSerializerOptions.WriteIndented = true); as it's explain in README.
    Then builder.Services.AddScoped<StorageManagement>(); or builder.Services.AddScoped(p => new StorageManagement(p.GetRequiredSerice<ILocalStorageService>()));

    But your service should take a ILocalStorageService not a LocalStorageService instance :

    public class StorageManagement
    {
        public StorageManagement(ILocalStorageService localStorage)
        {
            //How to initialize it here?
        }
    }