using Features.Emails.Templates.Mail;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.Web.HtmlRendering;
using Microsoft.Extensions.Logging;
namespace Features.Emails.Templates.Rendering;
///
/// Service for rendering Razor email templates to HTML using HtmlRenderer.
///
public class EmailTemplateProvider(IServiceProvider serviceProvider, ILoggerFactory loggerFactory)
: IEmailTemplateProvider
{
///
public async Task RenderUserRegisteredEmailAsync(
string username,
string confirmationLink
)
{
Dictionary parameters = new()
{
{ nameof(UserRegistration.Username), username },
{ nameof(UserRegistration.ConfirmationLink), confirmationLink },
};
return await RenderComponentAsync(parameters);
}
///
public async Task RenderResendConfirmationEmailAsync(
string username,
string confirmationLink
)
{
Dictionary parameters = new()
{
{ nameof(ResendConfirmation.Username), username },
{ nameof(ResendConfirmation.ConfirmationLink), confirmationLink },
};
return await RenderComponentAsync(parameters);
}
///
/// Creates a scoped , dispatches the render onto its renderer thread,
/// and returns the resulting HTML string.
///
private async Task RenderComponentAsync(
Dictionary parameters
)
where TComponent : IComponent
{
await using HtmlRenderer htmlRenderer = new(serviceProvider, loggerFactory);
string html = await htmlRenderer.Dispatcher.InvokeAsync(async () =>
{
ParameterView parameterView = ParameterView.FromDictionary(parameters);
HtmlRootComponent output = await htmlRenderer.RenderComponentAsync(
parameterView
);
return output.ToHtmlString();
});
return html;
}
}