Search code examples
dependency-injectionmodal-dialogblazorblazor-componentblazored

Using Blazored.Modal, from a non-component class, should I expect a Modal dialog to appear when I call IModalService.Show<>?


Ordinarily when using Blazored.Modal, a Modal dialog appears when I call IModalService.Show<> from a component, when IModalService is injected, which works great.

Should I expect a Modal dialog to appear when I call IModalService.Show<> from a method in a plain old C# class that is injected into a component (where IModalService is of course injected via the constructor)? The method is called from the component, of course.

I couldn't imagine why it wouldn't--after all, the runtime is injecting the same IModalService into both, right? But it does not and I don't understand why not. Do you?

using Blazored.Modal.Services;
namespace ...;
public class Class1 : IClass1
{
    public Class1(IModalService modal)
    {
        Modal = modal ?? throw new ArgumentNullException(nameof(modal));
    }
    protected IModalService Modal { get; set; }

    public void Show()
    {
        Modal.Show<MyDialog>();
    }
}

Then, from the component:

@using Blazored.Modal.Services;
@inject IClass1 class1;
@inject IModalService modal;
<button @onclick="class1.Show" >Show it</button> @* doesn't work *@
<button @onclick="@() => modal.Show<MyDialog>()" >Show it</button> @* works *@

(Also asked here.)


Solution

  • I tried to replicate your scenario. When I tried to consume IModalService from a singleton service I got the following error:

    Cannot consume scoped service 'Blazored.Modal.Services.IModalService' from singleton 'BlazorWebAssembly.Client.Services.IMyModalService'.

    After changing my service to scoped everything worked as expected and I was able to show modals.