wiki
wiki

Reputation: 2033

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(//?));

Upvotes: 0

Views: 1640

Answers (2)

Mister Magoo
Mister Magoo

Reputation: 8964

You are not using the Interface ILocalStorageServer in your constructor, it should be

public class StorageManagement
{
    private readonly ILocalStorageService LocalStorage;
    
    public StorageManagement(ILocalStorageService localStorage)
    {
        LocalStorage = localStorage;
    }
}

Upvotes: 0

agua from mars
agua from mars

Reputation: 17424

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?
    }
}

Upvotes: 1

Related Questions