Files
DigitalData.MessagingService/src/presentation/DigitalData.MessagingService.Client/EmailSender.cs
TekH 3cd8841e80 Refactor Email to EmailContext across codebase
Replaced the `Email` record with the new `EmailContext` record to introduce additional context and functionality in email handling. Updated property definitions to distinguish between .NET Framework (`set`) and other frameworks (`init`).

Modified `SendingEmailEvent` to use `EmailContext` for the `Mail` property. Updated mappings in `EmailMappingProfile` to map `SendEmailCommand` to `EmailContext`. Adjusted `SendEmailCommandHandler` to use `EmailContext` when mapping requests.

Refactored `EmailSender` to use `EmailContext` in its `Send` method, including updates to method signatures and documentation. Updated all related test classes (`EmailSenderTests`, `EmailSenderUrlOverloadTests`, `SendingEmailPublisherTests`) to validate the behavior of `EmailContext`, ensuring consistency and thorough testing of the transition.

These changes ensure compatibility across frameworks and improve the maintainability of the email handling process.
2026-08-05 14:06:41 +02:00

135 lines
6.0 KiB
C#

using DigitalData.MessagingService.Publisher;
using DigitalData.MessagingService.Abstraction;
using DigitalData.MessagingService.RabbitMQ;
using Microsoft.Extensions.DependencyInjection;
namespace DigitalData.MessagingService.Client;
/// <summary>
/// Provides a static, self-contained client for sending emails via RabbitMQ
/// without requiring a host-level dependency injection container.
/// </summary>
/// <remarks>
/// This class manages its own internal <see cref="IServiceProvider"/> using a
/// <see cref="Lazy{T}"/> pattern so the DI container is only built once,
/// on the first call to <see cref="ConnectRabbitMq(Action{RabbitMqConfiguration}, OnReconnect)"/>.
/// </remarks>
public static class EmailSender
{
/// <summary>
/// Internal event used to accumulate service registrations before the
/// <see cref="IServiceProvider"/> is built. Handlers are added by
/// <see cref="ConnectRabbitMq(Action{RabbitMqConfiguration}, OnReconnect)"/> and invoked exactly once during
/// lazy initialization.
/// </summary>
private static event Action<IServiceCollection> ConfigureServices = delegate { };
/// <summary>
/// The lazily-initialized internal service provider.
/// Built on first access by invoking all registered
/// <see cref="ConfigureServices"/> handlers.
/// </summary>
private static readonly Lazy<IServiceProvider> LazyProvider = new(() =>
{
var services = new ServiceCollection();
services.AddLogging();
ConfigureServices?.Invoke(services);
return services.BuildServiceProvider();
});
/// <summary>
/// Gets a value indicating whether the messaging service has been connected
/// and the internal <see cref="IServiceProvider"/> has been initialized.
/// </summary>
/// <value>
/// <see langword="true"/> if <see cref="ConnectRabbitMq(Action{RabbitMqConfiguration}, OnReconnect)"/> has been called
/// and the provider is built; otherwise <see langword="false"/>.
/// </value>
public static bool IsConnected => LazyProvider.IsValueCreated;
/// <summary>
/// Configures and establishes a connection to RabbitMQ, then initializes
/// the internal dependency injection container.
/// </summary>
/// <param name="configure">
/// A delegate used to configure the <see cref="RabbitMqConfiguration"/>,
/// such as host, port, credentials, and exchange settings.
/// </param>
/// <param name="onReconnect">
/// Controls the behavior when this method is called while already connected.
/// Defaults to <see cref="OnReconnect.ThrowException"/>.
/// </param>
/// <exception cref="InvalidOperationException">
/// Thrown when the service is already connected and
/// <paramref name="onReconnect"/> is <see cref="OnReconnect.ThrowException"/>.
/// </exception>
public static void ConnectRabbitMq(Action<RabbitMqConfiguration> configure, OnReconnect onReconnect = OnReconnect.ThrowException)
{
if(IsConnected && onReconnect == OnReconnect.ThrowException)
throw new InvalidOperationException("Messaging service is already connected.");
ConfigureServices += services => services.AddMessagingServicePublisher(configure);
_ = LazyProvider.Value; // Force initialization
}
/// <summary>
/// Configures and establishes a connection to RabbitMQ using a URL, then initializes
/// the internal dependency injection container.
/// </summary>
/// <param name="url">
/// The RabbitMQ server URL (e.g. <c>amqp://hostname:5672/virtualhost</c>).
/// The host, port, and virtual host are extracted from this URL.
/// </param>
/// <param name="username">The username used to authenticate with RabbitMQ.</param>
/// <param name="password">The password used to authenticate with RabbitMQ.</param>
/// <param name="onReconnect">
/// Controls the behavior when this method is called while already connected.
/// Defaults to <see cref="OnReconnect.ThrowException"/>.
/// </param>
/// <exception cref="InvalidOperationException">
/// Thrown when the service is already connected and
/// <paramref name="onReconnect"/> is <see cref="OnReconnect.ThrowException"/>.
/// </exception>
public static void ConnectRabbitMq(string url, string username, string password, OnReconnect onReconnect = OnReconnect.ThrowException)
{
var uri = new Uri(url);
ConnectRabbitMq(cfg =>
{
cfg.HostName = uri.Host;
cfg.Port = uri.IsDefaultPort ? 5672 : uri.Port;
cfg.UserName = username;
cfg.Password = password;
if (!string.IsNullOrEmpty(uri.AbsolutePath) && uri.AbsolutePath != "/")
cfg.VirtualHost = Uri.UnescapeDataString(uri.AbsolutePath.TrimStart('/'));
}, onReconnect);
}
/// <summary>
/// Enqueues the specified email to the RabbitMQ messaging pipeline.
/// </summary>
/// <param name="email">The outgoing email data to enqueue.</param>
/// <exception cref="InvalidOperationException">
/// Thrown when <see cref="ConnectRabbitMq(Action{RabbitMqConfiguration}, OnReconnect)"/> has not been called prior to sending.
/// </exception>
/// <remarks>
/// This method maps <see cref="EmailContext"/> to <see cref="SendingEmailEvent"/>,
/// then resolves <see cref="ISendingEmailPublisher"/> from the internal
/// service provider and calls <c>EnqueueAsync</c> in a fire-and-forget manner.
/// Ensure that any unhandled exceptions from the async operation are handled
/// at the publisher level.
/// </remarks>
public static void Send(EmailContext email)
{
if(!IsConnected)
throw new InvalidOperationException("Messaging service is not connected. Call ConnectRabbitMq first.");
var publisher = LazyProvider.Value.GetRequiredService<ISendingEmailPublisher>();
publisher.EnqueueAsync(new SendingEmailEvent()
{
Id = Guid.NewGuid(),
Mail = email,
QueuedAt = DateTime.Now
});
}
}