Refactor the `DependencyInjection` class to enhance the validation and setup process for `RabbitMQ` when used as the `ConsumerType`. Remove the outdated logic for adding an HTTP client based on `options.ApiUrl`. Introduce a check for `options.RabbitMQ` and throw a detailed `InvalidOperationException` if it is missing. Use `services.AddMessagingServiceClient` to configure the messaging service client with the appropriate section name.
52 lines
2.5 KiB
C#
52 lines
2.5 KiB
C#
using DigitalData.MessagingService.Client;
|
|
using EnvelopeGenerator.Application.Common.Interfaces.Services.Notification;
|
|
using EnvelopeGenerator.Infrastructure.Notification.Configuration;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
namespace EnvelopeGenerator.Infrastructure.Notification;
|
|
|
|
public static class DependencyInjection
|
|
{
|
|
public static IServiceCollection AddNotificationInfrastructure(this IServiceCollection services, IConfiguration configuration, string sectionName = NotificationOptions.SectionName)
|
|
{
|
|
var ntfConfiguration = configuration.GetSection(sectionName);
|
|
services.Configure<NotificationOptions>(ntfConfiguration);
|
|
|
|
var options = ntfConfiguration.Get<NotificationOptions>()
|
|
?? throw new InvalidOperationException(
|
|
$"Failed to bind configuration section '{sectionName}' to {nameof(NotificationOptions)}. Ensure the section exists and is correctly configured.");
|
|
|
|
switch (options.ConsumerType)
|
|
{
|
|
case ConsumerType.API:
|
|
if (options.ApiUrl is string apiUrl)
|
|
services.AddMessagingServiceHttpClient(opt =>
|
|
{
|
|
opt.BaseAddress = new Uri(apiUrl);
|
|
// Additional configuration for the MessagingServiceHttpClient can be added here if needed
|
|
});
|
|
else
|
|
throw new InvalidOperationException(
|
|
$"MessagingServiceApiUrl must be provided when ClientType is set to Api in the '{sectionName}' configuration section.");
|
|
break;
|
|
case ConsumerType.RabbitMQ:
|
|
if (options.RabbitMQ is null)
|
|
throw new InvalidOperationException(
|
|
$"Missing RabbitMQ configuration. " +
|
|
$"When ConsumerType is set to RabbitMQ, '{sectionName}:{nameof(NotificationOptions.RabbitMQ)}' must be configured.");
|
|
|
|
services.AddMessagingServiceClient(
|
|
configuration,
|
|
rabbitMqConnectionSectionName: $"{sectionName}:{nameof(NotificationOptions.RabbitMQ)}");
|
|
break;
|
|
default:
|
|
throw new InvalidOperationException(
|
|
$"Unsupported ConsumerType '{options.ConsumerType}' in the '{sectionName}' configuration section.");
|
|
}
|
|
|
|
services.AddScoped<IEnvelopeNotificationService, EnvelopeNotificationService>();
|
|
return services;
|
|
}
|
|
}
|