Add ConnectRabbitMq method to EmailSender class
Introduce a new static method `ConnectRabbitMq` in the `EmailSender` class to configure and establish RabbitMQ connections using a URL, username, and password. The method extracts connection details (host, port, virtual host) from the URL and supports optional behavior for reconnection scenarios via the `onReconnect` parameter. Added `using System;` to support the `Uri` class.
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
using DigitalData.MessagingService.Publisher.Abstraction;
|
||||
using DigitalData.MessagingService.RabbitMQ;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
|
||||
namespace DigitalData.MessagingService.Client.DependencyInjection;
|
||||
|
||||
@@ -71,6 +72,39 @@ public static class EmailSender
|
||||
_ = 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 event to the RabbitMQ messaging pipeline.
|
||||
/// </summary>
|
||||
|
||||
Reference in New Issue
Block a user