Ted
Ted

Reputation: 20184

Blazor: InvalidOperationException while attempting to activate custom service

I am testing out Blazor and now trying to get a grip regarding services and custom services.

The problem is I get this error message when starting the Blazor application:

WASM: System.InvalidOperationException: Unable to resolve service for type 'Blazor.Extensions.Storage.Interfaces.IStorage' while attempting to activate 'BlazorTest.Services.MyLocalStorage'.

  1. My own custom service MyLocalStorage requires another service to access the browsers local storage; in this case I am using Blazor.Extensions.Storage
  2. According to this page on learn.microsoft.com, a custom service that depends on another service needs to have a constructor to support it: "Constructor injection must be used instead. Required services are added by adding parameters to the service's constructor. When dependency injection creates the service, it recognizes the services it requires in the constructor and provides them accordingly."

So, my ConfigureServices in Startup.cs looks like this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddStorage(); // <-- extension method for Blazor.Extensions.Storage
    services.AddSingleton<IMyLocalStorage, MyLocalStorage>();
}

and my custom service:

public interface IMyLocalStorage
{
    Task<string> GetAuthToken();
    Task<string> GetDeviceUUID();
    Task SetAuthToken(string authToken);
    Task SetDeviceUuid(string deviceUuid);
}

public class MyLocalStorage : IMyLocalStorage
{

    private readonly IStorage storage;

    public MyLocalStorage(IStorage storage)
    {
        this.storage = storage;
    }
    // bla bla implementation
}

I thought this was the only thing required, but it still fails as can be seen above.

Note that if I skip my own custom serivce and use the Blazor.Extensions.Storage package directly, it works without any issues.

Im running VS2019 Preview 16.2.0 and .NET Core 3.0.0.

Upvotes: 1

Views: 907

Answers (1)

Simply Ged
Simply Ged

Reputation: 8642

If you take a look at the Blazor Storage code here you can see it does not register the IStorage interface.

Further inspection of the SessionStorage and LocalStorage classes shows that both implement IStorage so even if you did register IStorage you would need to clarify which class you want to inject.

It looks like you need to inject SessionStorage or LocalStorage in your constructor instead.

public class MyLocalStorage : IMyLocalStorage
{
    private readonly LocalStorage storage;

    public MyLocalStorage(LocalStorage storage)
    {
        this.storage = storage;
    }
    // bla bla implementation
}

Upvotes: 4

Related Questions