Creating helper class with injected IModalService #372
-
Hello, I am trying to understand if my approach to creating a modal helper class is correct, or if I am creating an issue between cascaded parameters and the DI system. I have an app that call a lot of complex models (forms, in-depth display windows, etc.) and a lot of simple modals (Confirm/Cancel dialogs, simple acknowledgements, etc.). I am calling the complex modals directly within the calling components as outlined in the Wiki, since they are passing in parameters and doing various actions with the returned objects. However, I am trying to make a helper class for the simple windows where I can inject the helper class, call a simple method with string parameters for the header and body text, and get back a bool if they user confirms or not. That way, I can control all of my simple modals from one place and call them with just one line. To do this, I created a It all seems to be working properly, but I'm not sure if I should have some concerns about having I can provide more code if needed, but here is a sample showing how I am calling confirm/cancel modals Helper Class: public class ModalManager
{
private IModalService modal { get; set; }
public ModalManager(IModalService modal)
{
this.modal = modal;
}
public async Task<bool> CallConfirmModal(string header, string message)
{
var parameters = new ModalParameters();
parameters.Add(nameof(ConfirmModal.Header), header);
parameters.Add(nameof(ConfirmModal.Message), message);
var closeModal = modal.Show<ConfirmModal>("", parameters);
var result = await closeModal.Result;
bool isConfirmed = (bool)result.Data;
return isConfirmed;
}
} Helper Class Scoping in services.AddScoped<ModalManager>(); Calling component relevant code @inject ModalManager ModalManager
@code{
private async Task ShowCloseProjectModal()
{
string header = "Close Project";
string message = "Would you like to close this project?";
bool isConfirmed = await ModalManager.CallConfirmModal(header, message);
if (isConfirmed)
{
//Do things here to close the project. Modal is already closed at this point
}
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
There shouldn't be any issues as the |
Beta Was this translation helpful? Give feedback.
There shouldn't be any issues as the
IModalService
instance that is cascaded is injected by DI initially. So when you request aIModalService
instance into your helper service, you're getting the same one as it's registered as Scoped with the service container.