I have a Blazor Web App .Net 8 project. I want to register the JsMethods service in the Client Program.cs file
//JsMethods Service
namespace QK.Services.Js
{
public interface IJsMethods
{
Task RunJsCommand(string command);
}
public class JsMethods : IJsMethods
{
private readonly IJSRuntime _jsRuntime;
public JsMethods(IJSRuntime jsRuntime)
{
_jsRuntime = jsRuntime;
}
public async Task RunJsCommand(string command)
{
await _jsRuntime.InvokeVoidAsync(command);
}
}
}
// Program.cs in client
builder.Services.AddScoped<IJsMethods, JsMethods>();
Now I want to run my service in HomeCarousel Component
namespace QK.Client.Components
{
public class HomeCarouselBase : ComponentBase
{
[Inject] private ICall call { get; set; }
[Inject] public ImageHelper.IImgService _ImgService { get; set; }
[Inject] private IJsMethods _jsMethods { get; set; }
public IReadOnlyList<Dto.MainSlider.ListDto>? Sliders { get; set; }
protected override async Task OnInitializedAsync()
{
Sliders = await call.CallApi<CallApi.EmptyModel, IReadOnlyList<Dto.MainSlider.ListDto>?>(QK.CallApi.Address.ListMainSlider,
new EmptyModel());
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await _jsMethods.RunJsCommand("swiperHome();");
}
}
}
But this gives an error
There is no registered service of type 'QK.Services.Js.IJsMethods'.
why ??
There is no registered service of type Service
The builder.Services.AddScoped<IJsMethods, JsMethods>();
need to be add to both client and Server project. For a Blazor Web app. When rendermode is InteractiveWebAssembly, the page will be still prerendered on server. So it still need the service exist in server project.
But as this page uses JS interop which wouldn't work on server. You may want to disable the prerender by using
@rendermode @(new InteractiveWebAssemblyRenderMode(false))