using System;
using Svrnty.CQRS.Events.Abstractions.Streaming;
using Svrnty.CQRS.Events.RabbitMQ.Delivery;
using Svrnty.CQRS.Events.RabbitMQ.Configuration;
using Svrnty.CQRS.Events.Abstractions.Delivery;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Svrnty.CQRS.Events.Abstractions;
namespace Svrnty.CQRS.Events.RabbitMQ;
///
/// Extension methods for registering RabbitMQ event delivery services.
///
public static class ServiceCollectionExtensions
{
///
/// Registers RabbitMQ as an external event delivery provider.
///
/// The service collection.
/// Configuration action for RabbitMQ options.
/// The service collection for method chaining.
///
///
/// services.AddRabbitMQEventDelivery(options =>
/// {
/// options.ConnectionString = "amqp://guest:guest@localhost:5672/";
/// options.ExchangePrefix = "myapp";
/// options.DefaultExchangeType = "topic";
/// options.EnablePublisherConfirms = true;
/// });
///
///
public static IServiceCollection AddRabbitMQEventDelivery(
this IServiceCollection services,
Action configure)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (configure == null)
throw new ArgumentNullException(nameof(configure));
// Configure options
services.Configure(configure);
// Register RabbitMQEventDeliveryProvider as both IEventDeliveryProvider and IExternalEventDeliveryProvider
services.TryAddSingleton();
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton(sp => sp.GetRequiredService());
// Register as hosted service to ensure Start/StopAsync are called
services.AddHostedService();
return services;
}
///
/// Registers RabbitMQ as an external event delivery provider with connection string.
///
/// The service collection.
/// RabbitMQ connection string (amqp://...).
/// Optional additional configuration.
/// The service collection for method chaining.
///
///
/// services.AddRabbitMQEventDelivery("amqp://guest:guest@localhost:5672/");
///
///
public static IServiceCollection AddRabbitMQEventDelivery(
this IServiceCollection services,
string connectionString,
Action? configure = null)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (string.IsNullOrWhiteSpace(connectionString))
throw new ArgumentException("Connection string cannot be null or whitespace.", nameof(connectionString));
return services.AddRabbitMQEventDelivery(options =>
{
options.ConnectionString = connectionString;
configure?.Invoke(options);
});
}
}