Search code examples
c#entity-frameworkblazor-webassembly

Calling interface method in razor page throws unhandled exception


Unhandled exception rendering component:

Cannot provide a value for property _accountService on type Inventory_Management.Client.Pages.Authentication.Login. There are no registered service of type Inventory_Management.Shared.Services.AccountService.

AccountService.cs

  public interface IAccountService
    {
        Task<IResult> Login(Identity model);
    }
    public class AccountService : IAccountService
    {
        public async Task<IResult> Login(Identity model){}
    }

login.razor

@inject IAccountService _accountService;
<div></div>
@code{
private async Task Submit()
    {
        var result = await _accountService.Login(userlogin); // Unhandled exception
    }
}

Followed the Github sample, it doesn't have any scope in the startup class. https://github.com/iammukeshm/CleanArchitecture.WebApi.

References

Client-> Pages-> Authentication-> Login.razor.cs
Infrastructure-> Identity-> Authentication->IAuthenticationManager
Server-> Extensions -> ServiceCollectionExtension.cs
startup.cs -> services.AddServerLocalization();

Solution

  • You need to have IAccountService (in the example you are trying to follow - see ServiceExtensions.AddIdentityInfrastructure and call to it in the Startup class) registered, for example with;

    services.AddScoped<IAccountService, AccountService>(); // also you should register all AccountService's dependencies
    

    and then resolve the interface, not the implementation:

    @inject IAccountService _accountService;
    <div></div>
    @code{
    private async Task Submit()
        {
            var result = await _accountService.Login(userlogin); // Unhandled exception
        }
    }