Compare commits
16 Commits
8ff8a9e58b
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 05d16bb32c | |||
| 3e86d4cfe2 | |||
| c0e0fa3ba1 | |||
| 4a39e3f92b | |||
| f799cdf2c4 | |||
| 50b92115bb | |||
| a7d8b3412b | |||
| 85d1e844b3 | |||
| 888f01ea95 | |||
| 034d81f7f6 | |||
| eed9a0e915 | |||
| ad2a5240d2 | |||
| 51d8931dbe | |||
| 35094529bb | |||
| 8cfa803cd3 | |||
| 82be3c5a4f |
@@ -0,0 +1,19 @@
|
|||||||
|
#if NET
|
||||||
|
using DigitalData.MessagingService.Application.EmailSending.Commands;
|
||||||
|
|
||||||
|
namespace DigitalData.MessagingService.Application.Common.Interfaces;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
/// </summary>
|
||||||
|
public interface IMessagingServiceClient
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="command"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public Task<Guid> SendAsync(PublishEmailViaSmtpCommand command, CancellationToken cancellationToken = default);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
#if NET
|
#if NET
|
||||||
using FluentValidation;
|
using FluentValidation;
|
||||||
using Microsoft.Extensions.Configuration;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
|
|
||||||
@@ -11,25 +10,22 @@ namespace DigitalData.MessagingService.Application.DependencyInjection;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public static class DependencyInjection
|
public static class DependencyInjection
|
||||||
{
|
{
|
||||||
public static IServiceCollection AddMessagingServiceApplication(this IServiceCollection services, Action<MessagingServiceApplicationConfiguration> configure)
|
public static IServiceCollection AddMessagingServiceApplication(this IServiceCollection services, string? luckyPennySoftLicenseKey = null)
|
||||||
{
|
{
|
||||||
var assembly = Assembly.GetExecutingAssembly();
|
var assembly = Assembly.GetExecutingAssembly();
|
||||||
|
|
||||||
var configuration = new MessagingServiceApplicationConfiguration(services);
|
|
||||||
configure(configuration);
|
|
||||||
configuration.EnsureConfigured();
|
|
||||||
|
|
||||||
// MediatR - Register all handlers
|
// MediatR - Register all handlers
|
||||||
services.AddMediatR(config =>
|
services.AddMediatR(config =>
|
||||||
{
|
{
|
||||||
config.LicenseKey = configuration.LuckyPennySoftLicenseKey;
|
config.LicenseKey = luckyPennySoftLicenseKey;
|
||||||
config.RegisterServicesFromAssembly(assembly);
|
config.RegisterServicesFromAssembly(assembly);
|
||||||
});
|
});
|
||||||
|
|
||||||
// AutoMapper - Use built-in DI extension (AutoMapper 16.2.0+)
|
// AutoMapper - Use built-in DI extension (AutoMapper 16.2.0+)
|
||||||
services.AddAutoMapper(config =>
|
services.AddAutoMapper(config =>
|
||||||
{
|
{
|
||||||
config.LicenseKey = configuration.LuckyPennySoftLicenseKey;
|
if (luckyPennySoftLicenseKey is not null)
|
||||||
|
config.LicenseKey = luckyPennySoftLicenseKey;
|
||||||
config.AddMaps(assembly);
|
config.AddMaps(assembly);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -38,14 +34,5 @@ public static class DependencyInjection
|
|||||||
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static IServiceCollection AddMessagingServiceApplication(this IServiceCollection services, IConfiguration configuration)
|
|
||||||
{
|
|
||||||
return services.AddMessagingServiceApplication(cfg =>
|
|
||||||
{
|
|
||||||
cfg.SetLuckyPennySoftLicenseKey(configuration);
|
|
||||||
cfg.ConfigureEmailAccounts(configuration);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
#if NET
|
|
||||||
using DigitalData.MessagingService.Application.Common.Options;
|
|
||||||
using Microsoft.Extensions.Configuration;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
|
|
||||||
namespace DigitalData.MessagingService.Application.DependencyInjection;
|
|
||||||
|
|
||||||
public partial class MessagingServiceApplicationConfiguration
|
|
||||||
{
|
|
||||||
private IServiceCollection Services { get; }
|
|
||||||
|
|
||||||
private (bool LuckyPennySoftLicenseKey, bool EmailAccounts) _configured = (LuckyPennySoftLicenseKey: false, EmailAccounts: false);
|
|
||||||
|
|
||||||
internal MessagingServiceApplicationConfiguration(IServiceCollection services)
|
|
||||||
{
|
|
||||||
Services = services;
|
|
||||||
}
|
|
||||||
|
|
||||||
internal void EnsureConfigured()
|
|
||||||
{
|
|
||||||
if (!_configured.LuckyPennySoftLicenseKey)
|
|
||||||
{
|
|
||||||
throw new InvalidOperationException("LuckyPennySoftLicenseKey is not configured. Please call SetLuckyPennySoftLicenseKey() or SetLuckyPennySoftLicenseKey(IConfiguration) in DI configuration.");
|
|
||||||
}
|
|
||||||
if (!_configured.EmailAccounts)
|
|
||||||
{
|
|
||||||
throw new InvalidOperationException("EmailAccountsOptions is not configured. Please call ConfigureEmailAccountsOptions() or ConfigureEmailAccounts(IConfiguration) in DI configuration.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#region LuckyPennySoftLicenseKey
|
|
||||||
internal string? LuckyPennySoftLicenseKey { get; set; } = null;
|
|
||||||
|
|
||||||
public MessagingServiceApplicationConfiguration SetLuckyPennySoftLicenseKey(string licenseKey)
|
|
||||||
{
|
|
||||||
if (string.IsNullOrWhiteSpace(licenseKey))
|
|
||||||
throw new InvalidOperationException("LuckyPennySoftLicenseKey is not configured. Please call SetLuckyPennySoftLicenseKey() or SetLuckyPennySoftLicenseKey(IConfiguration) in DI configuration.");
|
|
||||||
|
|
||||||
LuckyPennySoftLicenseKey = licenseKey;
|
|
||||||
_configured.LuckyPennySoftLicenseKey = true;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public MessagingServiceApplicationConfiguration SetLuckyPennySoftLicenseKey(IConfiguration configuration, string key = "LuckyPennySoftLicenseKey")
|
|
||||||
{
|
|
||||||
return SetLuckyPennySoftLicenseKey(configuration.GetValue<string>(key) ?? string.Empty);
|
|
||||||
}
|
|
||||||
#endregion LuckyPennySoftLicenseKey
|
|
||||||
|
|
||||||
#region EmailAccountsOptions
|
|
||||||
/// <summary>
|
|
||||||
/// Ignores whether EmailAccountsOptions is configured or not. Use this method if you just want to publish messages to the messaging service; not to send
|
|
||||||
/// emails. If you want to consume the messaging service to send emails, you must configure EmailAccountsOptions using ConfigureEmailAccountsOptions() or
|
|
||||||
/// ConfigureEmailAccounts(IConfiguration).
|
|
||||||
/// </summary>
|
|
||||||
/// <returns></returns>
|
|
||||||
public MessagingServiceApplicationConfiguration PublishOnly()
|
|
||||||
{
|
|
||||||
_configured.EmailAccounts = true;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public MessagingServiceApplicationConfiguration ConfigureEmailAccountsOptions(Action<EmailAccountsOptions> configureOptions)
|
|
||||||
{
|
|
||||||
Services.Configure(configureOptions);
|
|
||||||
_configured.EmailAccounts = true;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public MessagingServiceApplicationConfiguration ConfigureEmailAccounts(IConfiguration configuration, string sectionName = EmailAccountsOptions.SectionName)
|
|
||||||
{
|
|
||||||
Services.Configure<EmailAccountsOptions>(configuration.GetSection(sectionName));
|
|
||||||
_configured.EmailAccounts = true;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
#endregion EmailAccountsOptions
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
#if NET
|
||||||
|
using DigitalData.MessagingService.Application.EmailAccounts.Queries;
|
||||||
|
|
||||||
|
namespace DigitalData.MessagingService.Application.EmailSending.Commands;
|
||||||
|
|
||||||
|
public static class GetEmailAccountQueryExtensions
|
||||||
|
{
|
||||||
|
public static GetEmailAccountQuery ToSender(this string emailAddress)
|
||||||
|
{
|
||||||
|
return new GetEmailAccountQuery
|
||||||
|
{
|
||||||
|
Username = emailAddress
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -17,6 +17,10 @@ namespace DigitalData.MessagingService.Application.EmailSending.Commands;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public record PublishEmailViaSmtpCommand : IRequest<Guid>
|
public record PublishEmailViaSmtpCommand : IRequest<Guid>
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Specifies the sender's email account to resolve, identified by either its Id or Username.
|
||||||
|
/// Use <see cref="GetEmailAccountQueryExtensions.ToSender(string)"/> to create a query from an email address.
|
||||||
|
/// </summary>
|
||||||
public required GetEmailAccountQuery Sender { get; init; }
|
public required GetEmailAccountQuery Sender { get; init; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ using Microsoft.EntityFrameworkCore;
|
|||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
|
|
||||||
namespace DigitalData.MessagingService.Infrastructure;
|
namespace DigitalData.MessagingService.Infrastructure.DependencyInjection;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Dependency injection configuration for Infrastructure layer
|
/// Dependency injection configuration for Infrastructure layer
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
using DigitalData.MessagingService.Infrastructure.Options;
|
||||||
|
using DigitalData.MessagingService.RabbitMQ;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace DigitalData.MessagingService.Infrastructure.DependencyInjection;
|
||||||
|
|
||||||
|
public class MessagingServiceInfrastructureConfiguration
|
||||||
|
{
|
||||||
|
internal IServiceCollection Services { get; }
|
||||||
|
|
||||||
|
private (bool RabbitMqConnectionFactory, bool EmailAccounts) _configured = (false, false);
|
||||||
|
|
||||||
|
internal MessagingServiceInfrastructureConfiguration(IServiceCollection services)
|
||||||
|
{
|
||||||
|
Services = services;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void EnsureRabbitMqConnectionFactoryAdded()
|
||||||
|
{
|
||||||
|
if (!_configured.RabbitMqConnectionFactory)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("RabbitMQ connection factory has not been added. Please call AddRabbitMqConnectionFactory() before using this configuration.");
|
||||||
|
}
|
||||||
|
if(!_configured.EmailAccounts)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Email accounts options have not been configured. Please call ConfigureEmailAccountsOptions() or ConfigureEmailAccounts() before using this configuration.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public MessagingServiceInfrastructureConfiguration AddRabbitMqConnectionFactory(Action<RabbitMqConnectionConfiguration> configure)
|
||||||
|
{
|
||||||
|
Services.AddRabbitMqConnectionFactory(configure);
|
||||||
|
_configured.RabbitMqConnectionFactory = true;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MessagingServiceInfrastructureConfiguration AddRabbitMqConnectionFactory(IConfiguration configuration, string sectionName = RabbitMqConnectionConfiguration.SectionName)
|
||||||
|
{
|
||||||
|
Services.AddRabbitMqConnectionFactory(configuration, sectionName);
|
||||||
|
_configured.RabbitMqConnectionFactory = true;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
#region EmailAccountsOptions
|
||||||
|
public MessagingServiceInfrastructureConfiguration ConfigureEmailAccountsOptions(Action<EmailAccountsOptions> configureOptions)
|
||||||
|
{
|
||||||
|
Services.Configure(configureOptions);
|
||||||
|
_configured.EmailAccounts = true;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MessagingServiceInfrastructureConfiguration ConfigureEmailAccounts(IConfiguration configuration, string sectionName = EmailAccountsOptions.SectionName)
|
||||||
|
{
|
||||||
|
Services.Configure<EmailAccountsOptions>(configuration.GetSection(sectionName));
|
||||||
|
_configured.EmailAccounts = true;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
#endregion EmailAccountsOptions
|
||||||
|
}
|
||||||
@@ -38,8 +38,4 @@
|
|||||||
</Reference>
|
</Reference>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<Folder Include="Messaging\" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -1,40 +0,0 @@
|
|||||||
using DigitalData.MessagingService.RabbitMQ;
|
|
||||||
using Microsoft.Extensions.Configuration;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
|
|
||||||
namespace DigitalData.MessagingService.Infrastructure;
|
|
||||||
|
|
||||||
public class MessagingServiceInfrastructureConfiguration
|
|
||||||
{
|
|
||||||
internal IServiceCollection Services { get; }
|
|
||||||
|
|
||||||
private bool _rabbitMqConnectionFactoryAdded = false;
|
|
||||||
|
|
||||||
internal MessagingServiceInfrastructureConfiguration(IServiceCollection services)
|
|
||||||
{
|
|
||||||
Services = services;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void EnsureRabbitMqConnectionFactoryAdded()
|
|
||||||
{
|
|
||||||
if (!_rabbitMqConnectionFactoryAdded)
|
|
||||||
{
|
|
||||||
throw new InvalidOperationException("RabbitMQ connection factory has not been added. Please call AddRabbitMqConnectionFactory() before using this configuration.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public MessagingServiceInfrastructureConfiguration AddRabbitMqConnectionFactory(Action<RabbitMqConfiguration> configure)
|
|
||||||
{
|
|
||||||
Services.AddRabbitMqConnectionFactory(configure);
|
|
||||||
_rabbitMqConnectionFactoryAdded = true;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public MessagingServiceInfrastructureConfiguration AddRabbitMqConnectionFactory(IConfiguration configuration, string sectionName = RabbitMqConfiguration.SectionName)
|
|
||||||
{
|
|
||||||
Services.AddRabbitMqConnectionFactory(configuration, sectionName);
|
|
||||||
_rabbitMqConnectionFactoryAdded = true;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,10 +1,7 @@
|
|||||||
#if NET
|
#if NET
|
||||||
using DigitalData.MessagingService.Application.Common.Dto;
|
|
||||||
using DigitalData.MessagingService.Application.Common.Dto.EmailAccounts;
|
using DigitalData.MessagingService.Application.Common.Dto.EmailAccounts;
|
||||||
using DigitalData.MessagingService.Application.EmailAccounts.Commands;
|
|
||||||
using DigitalData.MessagingService.Domain.Entities;
|
|
||||||
|
|
||||||
namespace DigitalData.MessagingService.Application.Common.Options;
|
namespace DigitalData.MessagingService.Infrastructure.Options;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Wrapper options class that holds a list of <see cref="Dto.EmailAccount"/> entries
|
/// Wrapper options class that holds a list of <see cref="Dto.EmailAccount"/> entries
|
||||||
@@ -17,7 +17,7 @@ public sealed class SendingEmailConsumerPool : IAsyncDisposable
|
|||||||
private readonly int _concurrency;
|
private readonly int _concurrency;
|
||||||
|
|
||||||
public SendingEmailConsumerPool(
|
public SendingEmailConsumerPool(
|
||||||
IOptions<RabbitMqConfiguration> config,
|
IOptions<RabbitMqConnectionConfiguration> config,
|
||||||
IEmailService emailService,
|
IEmailService emailService,
|
||||||
IServiceScopeFactory scopeFactory,
|
IServiceScopeFactory scopeFactory,
|
||||||
RabbitMqConnectionFactory cnnFactory,
|
RabbitMqConnectionFactory cnnFactory,
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ namespace DigitalData.MessagingService.Infrastructure.Services.Background;
|
|||||||
public class ConsumerInitWorker(
|
public class ConsumerInitWorker(
|
||||||
SendingEmailConsumerPool ConsumerPool,
|
SendingEmailConsumerPool ConsumerPool,
|
||||||
ILogger<ConsumerInitWorker> Logger,
|
ILogger<ConsumerInitWorker> Logger,
|
||||||
IOptions<RabbitMqConfiguration> RabbitMqOptions,
|
IOptions<RabbitMqConnectionConfiguration> RabbitMqOptions,
|
||||||
ConsumerInitHealthCheck HealthCheck) : BackgroundService
|
ConsumerInitHealthCheck HealthCheck) : BackgroundService
|
||||||
{
|
{
|
||||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
using DigitalData.MessagingService.Application.Common.Interfaces;
|
using DigitalData.MessagingService.Application.Common.Interfaces;
|
||||||
using DigitalData.MessagingService.Application.Common.Interfaces.Repositories;
|
using DigitalData.MessagingService.Application.Common.Interfaces.Repositories;
|
||||||
using DigitalData.MessagingService.Application.Common.Options;
|
|
||||||
using DigitalData.MessagingService.Domain.Entities;
|
using DigitalData.MessagingService.Domain.Entities;
|
||||||
using DigitalData.MessagingService.Domain.Enums;
|
using DigitalData.MessagingService.Domain.Enums;
|
||||||
|
using DigitalData.MessagingService.Infrastructure.Options;
|
||||||
using Microsoft.Extensions.Caching.Memory;
|
using Microsoft.Extensions.Caching.Memory;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
|
|||||||
@@ -7,15 +7,20 @@ namespace DigitalData.MessagingService.Publisher;
|
|||||||
|
|
||||||
public static class DependencyInjection
|
public static class DependencyInjection
|
||||||
{
|
{
|
||||||
public static IServiceCollection AddMessagingServicePublisher(this IServiceCollection services, Action<MessagingServicePublisherConfiguration>? configure = null)
|
public static IServiceCollection AddMessagingServicePublisher(this IServiceCollection services)
|
||||||
{
|
{
|
||||||
var configuration = new MessagingServicePublisherConfiguration(services);
|
return services.AddSingleton<ISendingEmailPublisher, SendingEmailPublisher>();
|
||||||
|
}
|
||||||
|
|
||||||
configure?.Invoke(configuration);
|
public static IServiceCollection AddMessagingServicePublisher(this IServiceCollection services, Action<RabbitMqConnectionConfiguration> configureRabbitMqConnection)
|
||||||
|
{
|
||||||
|
services.AddRabbitMqConnectionFactory(configureRabbitMqConnection);
|
||||||
|
return services.AddMessagingServicePublisher();
|
||||||
|
}
|
||||||
|
|
||||||
// --- Email Queue (RabbitMQ) ---
|
public static IServiceCollection AddMessagingServicePublisher(this IServiceCollection services, IConfiguration configuration, string rabbitMqConnectionSectionName = RabbitMqConnectionConfiguration.SectionName)
|
||||||
services.AddSingleton<ISendingEmailPublisher, SendingEmailPublisher>();
|
{
|
||||||
|
services.AddRabbitMqConnectionFactory(configuration.GetSection(rabbitMqConnectionSectionName));
|
||||||
return services;
|
return services.AddMessagingServicePublisher();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
using DigitalData.MessagingService.RabbitMQ;
|
|
||||||
using Microsoft.Extensions.Configuration;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
|
|
||||||
namespace DigitalData.MessagingService.Publisher;
|
|
||||||
|
|
||||||
public class MessagingServicePublisherConfiguration
|
|
||||||
{
|
|
||||||
internal IServiceCollection Services { get; }
|
|
||||||
|
|
||||||
internal MessagingServicePublisherConfiguration(IServiceCollection services)
|
|
||||||
{
|
|
||||||
Services = services;
|
|
||||||
}
|
|
||||||
|
|
||||||
public MessagingServicePublisherConfiguration AddRabbitMqConnectionFactory(Action<RabbitMqConfiguration> configure)
|
|
||||||
{
|
|
||||||
Services.AddRabbitMqConnectionFactory(configure);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public MessagingServicePublisherConfiguration AddRabbitMqConnectionFactory(IConfiguration configuration, string sectionName = RabbitMqConfiguration.SectionName)
|
|
||||||
{
|
|
||||||
Services.AddRabbitMqConnectionFactory(configuration, sectionName);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -16,12 +16,12 @@ namespace DigitalData.MessagingService.Publisher;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class SendingEmailPublisher : ISendingEmailPublisher, IAsyncDisposable
|
public sealed class SendingEmailPublisher : ISendingEmailPublisher, IAsyncDisposable
|
||||||
{
|
{
|
||||||
private readonly RabbitMqConfiguration _config;
|
private readonly RabbitMqConnectionConfiguration _config;
|
||||||
private readonly ILogger<SendingEmailPublisher> _logger;
|
private readonly ILogger<SendingEmailPublisher> _logger;
|
||||||
private readonly RabbitMqConnectionFactory _cnnFactory;
|
private readonly RabbitMqConnectionFactory _cnnFactory;
|
||||||
private readonly Lazy<Task<IChannel>> _lazyChannel;
|
private readonly Lazy<Task<IChannel>> _lazyChannel;
|
||||||
|
|
||||||
public SendingEmailPublisher(IOptions<RabbitMqConfiguration> config, ILogger<SendingEmailPublisher> logger, RabbitMqConnectionFactory cnnFactory)
|
public SendingEmailPublisher(IOptions<RabbitMqConnectionConfiguration> config, ILogger<SendingEmailPublisher> logger, RabbitMqConnectionFactory cnnFactory)
|
||||||
{
|
{
|
||||||
_config = config.Value;
|
_config = config.Value;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
|
|||||||
@@ -9,36 +9,26 @@ namespace DigitalData.MessagingService.RabbitMQ
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public static class DependencyInjection
|
public static class DependencyInjection
|
||||||
{
|
{
|
||||||
private static IServiceCollection AddDefaultServices(this IServiceCollection services)
|
|
||||||
{
|
|
||||||
services.AddSingleton<RabbitMqConnectionFactory>();
|
|
||||||
return services;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Adds Infrastructure layer services to the DI container
|
/// Adds Infrastructure layer services to the DI container
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static IServiceCollection AddRabbitMqConnectionFactory(this IServiceCollection services, Action<RabbitMqConfiguration> configure)
|
public static IServiceCollection AddRabbitMqConnectionFactory(this IServiceCollection services, Action<RabbitMqConnectionConfiguration> configure)
|
||||||
{
|
{
|
||||||
services.AddDefaultServices();
|
|
||||||
|
|
||||||
// --- RabbitMQ Configuration ---
|
// --- RabbitMQ Configuration ---
|
||||||
services.Configure(configure);
|
services.Configure(configure);
|
||||||
|
|
||||||
return services;
|
return services.AddSingleton<RabbitMqConnectionFactory>();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Adds Infrastructure layer services to the DI container
|
/// Adds Infrastructure layer services to the DI container
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static IServiceCollection AddRabbitMqConnectionFactory(this IServiceCollection services, IConfiguration configuration, string sectionName = RabbitMqConfiguration.SectionName)
|
public static IServiceCollection AddRabbitMqConnectionFactory(this IServiceCollection services, IConfiguration configuration, string sectionName = RabbitMqConnectionConfiguration.SectionName)
|
||||||
{
|
{
|
||||||
services.AddDefaultServices();
|
|
||||||
|
|
||||||
// --- RabbitMQ Configuration ---
|
// --- RabbitMQ Configuration ---
|
||||||
services.Configure<RabbitMqConfiguration>(configuration.GetSection(sectionName));
|
services.Configure<RabbitMqConnectionConfiguration>(configuration.GetSection(sectionName));
|
||||||
|
|
||||||
return services;
|
return services.AddSingleton<RabbitMqConnectionFactory>();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,7 +3,7 @@ namespace DigitalData.MessagingService.RabbitMQ
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Configuration for RabbitMQ connection
|
/// Configuration for RabbitMQ connection
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class RabbitMqConfiguration
|
public class RabbitMqConnectionConfiguration
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Configuration section name in appsettings.json
|
/// Configuration section name in appsettings.json
|
||||||
@@ -12,7 +12,7 @@ namespace DigitalData.MessagingService.RabbitMQ
|
|||||||
{
|
{
|
||||||
private readonly CancellationTokenSource _consumerCts = new CancellationTokenSource();
|
private readonly CancellationTokenSource _consumerCts = new CancellationTokenSource();
|
||||||
|
|
||||||
private readonly RabbitMqConfiguration _config;
|
private readonly RabbitMqConnectionConfiguration _config;
|
||||||
|
|
||||||
private readonly ILogger<RabbitMqConnectionFactory>
|
private readonly ILogger<RabbitMqConnectionFactory>
|
||||||
#if nullable
|
#if nullable
|
||||||
@@ -41,7 +41,7 @@ namespace DigitalData.MessagingService.RabbitMQ
|
|||||||
return new AsyncEventingBasicConsumer(channel);
|
return new AsyncEventingBasicConsumer(channel);
|
||||||
}
|
}
|
||||||
|
|
||||||
public RabbitMqConnectionFactory(IOptions<RabbitMqConfiguration> config)
|
public RabbitMqConnectionFactory(IOptions<RabbitMqConnectionConfiguration> config)
|
||||||
{
|
{
|
||||||
_config = config.Value;
|
_config = config.Value;
|
||||||
_lazyConnectionProvider = new Lazy<Task<IConnection>>(async () =>
|
_lazyConnectionProvider = new Lazy<Task<IConnection>>(async () =>
|
||||||
|
|||||||
@@ -10,9 +10,9 @@
|
|||||||
<Authors>Digital Data GmbH</Authors>
|
<Authors>Digital Data GmbH</Authors>
|
||||||
<Company>Digital Data GmbH</Company>
|
<Company>Digital Data GmbH</Company>
|
||||||
<Product>DigitalData.MessagingService.API</Product>
|
<Product>DigitalData.MessagingService.API</Product>
|
||||||
<Version>2.1.0-beta</Version>
|
<Version>2.2.0-beta</Version>
|
||||||
<FileVersion>2.1.0.0</FileVersion>
|
<FileVersion>2.2.0.0</FileVersion>
|
||||||
<AssemblyVersion>2.1.0.0</AssemblyVersion>
|
<AssemblyVersion>2.2.0.0</AssemblyVersion>
|
||||||
<Copyright>Copyright © 2026 Digital Data GmbH. All rights reserved.</Copyright>
|
<Copyright>Copyright © 2026 Digital Data GmbH. All rights reserved.</Copyright>
|
||||||
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
|
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
using DigitalData.MessagingService.API.Middleware;
|
using DigitalData.MessagingService.API.Middleware;
|
||||||
using DigitalData.MessagingService.Application.DependencyInjection;
|
using DigitalData.MessagingService.Application.DependencyInjection;
|
||||||
using DigitalData.MessagingService.Infrastructure;
|
using DigitalData.MessagingService.Infrastructure.DependencyInjection;
|
||||||
using DigitalData.MessagingService.Infrastructure.Services.Background;
|
using DigitalData.MessagingService.Infrastructure.Services.Background;
|
||||||
using HealthChecks.UI.Client;
|
using HealthChecks.UI.Client;
|
||||||
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
|
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
|
||||||
@@ -65,10 +65,14 @@ try
|
|||||||
builder.Configuration.AddJsonFile("appsettings.Secrets.json", optional: true, reloadOnChange: true);
|
builder.Configuration.AddJsonFile("appsettings.Secrets.json", optional: true, reloadOnChange: true);
|
||||||
|
|
||||||
// Register Application layer (MediatR, AutoMapper, FluentValidation)
|
// Register Application layer (MediatR, AutoMapper, FluentValidation)
|
||||||
builder.Services.AddMessagingServiceApplication(builder.Configuration);
|
var LuckyPennySoftLicenseKey = builder.Configuration.GetValue<string>("LuckyPennySoftLicenseKey")
|
||||||
|
?? throw new InvalidOperationException("The required configuration value 'LuckyPennySoftLicenseKey' is missing. Please ensure it is properly configured.");
|
||||||
|
builder.Services.AddMessagingServiceApplication(LuckyPennySoftLicenseKey);
|
||||||
|
|
||||||
// Register Infrastructure layer (RabbitMQ, Repositories, etc.)
|
// Register Infrastructure layer (RabbitMQ, Repositories, etc.)
|
||||||
builder.Services.AddInfrastructure(cfg => cfg.AddRabbitMqConnectionFactory(builder.Configuration));
|
builder.Services.AddInfrastructure(cfg => cfg
|
||||||
|
.AddRabbitMqConnectionFactory(builder.Configuration)
|
||||||
|
.ConfigureEmailAccounts(builder.Configuration));
|
||||||
|
|
||||||
// Health checks — each check corresponds to a singleton registered in the Infrastructure layer
|
// Health checks — each check corresponds to a singleton registered in the Infrastructure layer
|
||||||
builder.Services.AddHealthChecks()
|
builder.Services.AddHealthChecks()
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
#if NET
|
||||||
|
using DigitalData.MessagingService.Application.Common.Interfaces;
|
||||||
|
using DigitalData.MessagingService.Application.DependencyInjection;
|
||||||
|
using DigitalData.MessagingService.Publisher;
|
||||||
|
using DigitalData.MessagingService.RabbitMQ;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace DigitalData.MessagingService.Client;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
/// </summary>
|
||||||
|
public static class DependencyInjection
|
||||||
|
{
|
||||||
|
private static IServiceCollection EnsureMessagingServiceClientNotRegistered(this IServiceCollection services)
|
||||||
|
{
|
||||||
|
if (services.Any(x => x.ServiceType == typeof(IMessagingServiceClient)))
|
||||||
|
throw new InvalidOperationException("IMessagingServiceClient is already registered. Register only one client implementation (MessagingServiceClient or MessagingServiceHttpClient).");
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IServiceCollection AddMessagingServiceClientDefault(this IServiceCollection services, string? luckyPennySoftLicenseKey = null)
|
||||||
|
{
|
||||||
|
services.EnsureMessagingServiceClientNotRegistered();
|
||||||
|
services.AddMessagingServiceApplication(luckyPennySoftLicenseKey);
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
#region DI Extensions
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="services"></param>
|
||||||
|
/// <param name="luckyPennySoftLicenseKey"></param>
|
||||||
|
/// <param name="configureRabbitMqConnection"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static IServiceCollection AddMessagingServiceClient(this IServiceCollection services, Action<RabbitMqConnectionConfiguration> configureRabbitMqConnection, string? luckyPennySoftLicenseKey = null)
|
||||||
|
{
|
||||||
|
services.AddMessagingServiceClientDefault(luckyPennySoftLicenseKey);
|
||||||
|
services.AddMessagingServicePublisher(configureRabbitMqConnection);
|
||||||
|
services.AddTransient<IMessagingServiceClient, MessagingServiceClient>();
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="services"></param>
|
||||||
|
/// <param name="luckyPennySoftLicenseKey"></param>
|
||||||
|
/// <param name="configuration"></param>
|
||||||
|
/// <param name="rabbitMqConnectionSectionName"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static IServiceCollection AddMessagingServiceClient(this IServiceCollection services, IConfiguration configuration, string? luckyPennySoftLicenseKey = null, string rabbitMqConnectionSectionName = RabbitMqConnectionConfiguration.SectionName)
|
||||||
|
{
|
||||||
|
services.AddMessagingServiceClientDefault(luckyPennySoftLicenseKey);
|
||||||
|
services.AddMessagingServicePublisher(configuration, rabbitMqConnectionSectionName);
|
||||||
|
services.AddTransient<IMessagingServiceClient, MessagingServiceClient>();
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Registers <see cref="MessagingServiceHttpClient"/> as <see cref="IMessagingServiceClient"/>.
|
||||||
|
/// Configure <see cref="HttpClient.BaseAddress"/> for the named client <c>MessagingServiceHttpClient</c>.
|
||||||
|
/// </summary>
|
||||||
|
public static IServiceCollection AddMessagingServiceHttpClient(this IServiceCollection services, Action<HttpClient> configureHttpClient)
|
||||||
|
{
|
||||||
|
services.EnsureMessagingServiceClientNotRegistered();
|
||||||
|
services.AddHttpClient(nameof(MessagingServiceHttpClient), configureHttpClient);
|
||||||
|
services.AddTransient<IMessagingServiceClient, MessagingServiceHttpClient>();
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Registers <see cref="MessagingServiceHttpClient"/> as <see cref="IMessagingServiceClient"/>.
|
||||||
|
/// Configure <see cref="HttpClient.BaseAddress"/> for the named client <c>MessagingServiceHttpClient</c> using the provided base address.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="services"></param>
|
||||||
|
/// <param name="baseAddress"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static IServiceCollection AddMessagingServiceHttpClient(IServiceCollection services, string baseAddress)
|
||||||
|
{
|
||||||
|
// do not call EnsureMessagingServiceClientNotRegistered here because AddMessagingServiceHttpClient is already calling it in the overload above
|
||||||
|
return services.AddMessagingServiceHttpClient(client => client.BaseAddress = new Uri(baseAddress));
|
||||||
|
}
|
||||||
|
#endregion DI Extensions
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -11,9 +11,9 @@
|
|||||||
<PackageIcon>icon.png</PackageIcon>
|
<PackageIcon>icon.png</PackageIcon>
|
||||||
<RepositoryUrl>http://git.dd:3000/AppStd/Rec.git</RepositoryUrl>
|
<RepositoryUrl>http://git.dd:3000/AppStd/Rec.git</RepositoryUrl>
|
||||||
<PackageTags>digital data messaging service api client</PackageTags>
|
<PackageTags>digital data messaging service api client</PackageTags>
|
||||||
<Version>1.0.5</Version>
|
<Version>3.0.0</Version>
|
||||||
<AssemblyVersion>1.0.5.0</AssemblyVersion>
|
<AssemblyVersion>3.0.0.0</AssemblyVersion>
|
||||||
<FileVersion>1.0.5.0</FileVersion>
|
<FileVersion>3.0.0.0</FileVersion>
|
||||||
<Description></Description>
|
<Description></Description>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
@@ -27,6 +27,7 @@
|
|||||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="10.0.10" />
|
<PackageReference Include="Microsoft.Extensions.Logging" Version="10.0.10" />
|
||||||
<PackageReference Include="RabbitMQ.Client" Version="7.2.1" />
|
<PackageReference Include="RabbitMQ.Client" Version="7.2.1" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.10" />
|
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.10" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.10" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
|
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
|
||||||
@@ -61,7 +62,7 @@
|
|||||||
|
|
||||||
<Target Name="EmbedProjectReferences" DependsOnTargets="ResolveReferences">
|
<Target Name="EmbedProjectReferences" DependsOnTargets="ResolveReferences">
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<BuildOutputInPackage Include="@(ReferenceCopyLocalPaths->WithMetadataValue('ReferenceSourceTarget','ProjectReference'))" />
|
<BuildOutputInPackage Include="@(ReferenceCopyLocalPaths->WithMetadataValue('ReferenceSourceTarget','ProjectReference'))" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
</Target>
|
</Target>
|
||||||
|
|
||||||
|
|||||||
@@ -13,14 +13,17 @@ namespace DigitalData.MessagingService.Client;
|
|||||||
/// <remarks>
|
/// <remarks>
|
||||||
/// This class manages its own internal <see cref="IServiceProvider"/> using a
|
/// This class manages its own internal <see cref="IServiceProvider"/> using a
|
||||||
/// <see cref="Lazy{T}"/> pattern so the DI container is only built once,
|
/// <see cref="Lazy{T}"/> pattern so the DI container is only built once,
|
||||||
/// on the first call to <see cref="ConnectRabbitMq(Action{RabbitMqConfiguration}, OnReconnect)"/>.
|
/// on the first call to <see cref="ConnectRabbitMq(Action{RabbitMqConnectionConfiguration}, OnReconnect)"/>.
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
|
#if NET
|
||||||
|
[Obsolete("Use MessagingServiceClient with dependency injection instead.")]
|
||||||
|
#endif
|
||||||
public static class EmailSender
|
public static class EmailSender
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Internal event used to accumulate service registrations before the
|
/// Internal event used to accumulate service registrations before the
|
||||||
/// <see cref="IServiceProvider"/> is built. Handlers are added by
|
/// <see cref="IServiceProvider"/> is built. Handlers are added by
|
||||||
/// <see cref="ConnectRabbitMq(Action{RabbitMqConfiguration}, OnReconnect)"/> and invoked exactly once during
|
/// <see cref="ConnectRabbitMq(Action{RabbitMqConnectionConfiguration}, OnReconnect)"/> and invoked exactly once during
|
||||||
/// lazy initialization.
|
/// lazy initialization.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static event Action<IServiceCollection> ConfigureServices = delegate { };
|
private static event Action<IServiceCollection> ConfigureServices = delegate { };
|
||||||
@@ -43,7 +46,7 @@ public static class EmailSender
|
|||||||
/// and the internal <see cref="IServiceProvider"/> has been initialized.
|
/// and the internal <see cref="IServiceProvider"/> has been initialized.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <value>
|
/// <value>
|
||||||
/// <see langword="true"/> if <see cref="ConnectRabbitMq(Action{RabbitMqConfiguration}, OnReconnect)"/> has been called
|
/// <see langword="true"/> if <see cref="ConnectRabbitMq(Action{RabbitMqConnectionConfiguration}, OnReconnect)"/> has been called
|
||||||
/// and the provider is built; otherwise <see langword="false"/>.
|
/// and the provider is built; otherwise <see langword="false"/>.
|
||||||
/// </value>
|
/// </value>
|
||||||
public static bool IsConnected => LazyProvider.IsValueCreated;
|
public static bool IsConnected => LazyProvider.IsValueCreated;
|
||||||
@@ -53,7 +56,7 @@ public static class EmailSender
|
|||||||
/// the internal dependency injection container.
|
/// the internal dependency injection container.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="configure">
|
/// <param name="configure">
|
||||||
/// A delegate used to configure the <see cref="RabbitMqConfiguration"/>,
|
/// A delegate used to configure the <see cref="RabbitMqConnectionConfiguration"/>,
|
||||||
/// such as host, port, credentials, and exchange settings.
|
/// such as host, port, credentials, and exchange settings.
|
||||||
/// </param>
|
/// </param>
|
||||||
/// <param name="onReconnect">
|
/// <param name="onReconnect">
|
||||||
@@ -64,12 +67,12 @@ public static class EmailSender
|
|||||||
/// Thrown when the service is already connected and
|
/// Thrown when the service is already connected and
|
||||||
/// <paramref name="onReconnect"/> is <see cref="OnReconnect.ThrowException"/>.
|
/// <paramref name="onReconnect"/> is <see cref="OnReconnect.ThrowException"/>.
|
||||||
/// </exception>
|
/// </exception>
|
||||||
public static void ConnectRabbitMq(Action<RabbitMqConfiguration> configure, OnReconnect onReconnect = OnReconnect.ThrowException)
|
public static void ConnectRabbitMq(Action<RabbitMqConnectionConfiguration> configure, OnReconnect onReconnect = OnReconnect.ThrowException)
|
||||||
{
|
{
|
||||||
if(IsConnected && onReconnect == OnReconnect.ThrowException)
|
if(IsConnected && onReconnect == OnReconnect.ThrowException)
|
||||||
throw new InvalidOperationException("Messaging service is already connected.");
|
throw new InvalidOperationException("Messaging service is already connected.");
|
||||||
|
|
||||||
ConfigureServices += services => services.AddMessagingServicePublisher(cfg => cfg.AddRabbitMqConnectionFactory(configure));
|
ConfigureServices += services => services.AddMessagingServicePublisher(configure);
|
||||||
_ = LazyProvider.Value; // Force initialization
|
_ = LazyProvider.Value; // Force initialization
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,7 +114,7 @@ public static class EmailSender
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="email">The outgoing email data to enqueue.</param>
|
/// <param name="email">The outgoing email data to enqueue.</param>
|
||||||
/// <exception cref="InvalidOperationException">
|
/// <exception cref="InvalidOperationException">
|
||||||
/// Thrown when <see cref="ConnectRabbitMq(Action{RabbitMqConfiguration}, OnReconnect)"/> has not been called prior to sending.
|
/// Thrown when <see cref="ConnectRabbitMq(Action{RabbitMqConnectionConfiguration}, OnReconnect)"/> has not been called prior to sending.
|
||||||
/// </exception>
|
/// </exception>
|
||||||
/// <remarks>
|
/// <remarks>
|
||||||
/// This method maps <see cref="EmailContext"/> to <see cref="SendingEmailEvent"/>,
|
/// This method maps <see cref="EmailContext"/> to <see cref="SendingEmailEvent"/>,
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
#if NET
|
||||||
|
using DigitalData.MessagingService.Application.Common.Interfaces;
|
||||||
|
using DigitalData.MessagingService.Application.EmailSending.Commands;
|
||||||
|
using MediatR;
|
||||||
|
|
||||||
|
namespace DigitalData.MessagingService.Client;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
/// </summary>
|
||||||
|
public class MessagingServiceClient(ISender sender) : IMessagingServiceClient
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="command"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public Task<Guid> SendAsync(PublishEmailViaSmtpCommand command, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
return sender.Send(command, cancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
#if NET
|
||||||
|
using DigitalData.MessagingService.Application.Common.Interfaces;
|
||||||
|
using DigitalData.MessagingService.Application.EmailAccounts.Queries;
|
||||||
|
using DigitalData.MessagingService.Application.EmailSending.Commands;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
|
||||||
|
namespace DigitalData.MessagingService.Client;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
/// </summary>
|
||||||
|
public class MessagingServiceHttpClient(IHttpClientFactory httpClientFactory) : IMessagingServiceClient
|
||||||
|
{
|
||||||
|
private sealed record SendEmailAcceptedResponse(Guid Id);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="command"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
/// <exception cref="HttpRequestException"></exception>
|
||||||
|
public async Task<Guid> SendAsync(PublishEmailViaSmtpCommand command, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var httpClient = httpClientFactory.CreateClient(nameof(MessagingServiceHttpClient));
|
||||||
|
|
||||||
|
var senderUsernameField = $"{nameof(PublishEmailViaSmtpCommand.Sender)}.{nameof(GetEmailAccountQuery.Username)}";
|
||||||
|
|
||||||
|
using var form = new MultipartFormDataContent
|
||||||
|
{
|
||||||
|
{ new StringContent(command.Sender.Username ?? string.Empty), senderUsernameField },
|
||||||
|
{ new StringContent(command.Subject), nameof(PublishEmailViaSmtpCommand.Subject) },
|
||||||
|
{ new StringContent(command.Body), nameof(PublishEmailViaSmtpCommand.Body) },
|
||||||
|
{ new StringContent(command.IsHtml.ToString().ToLowerInvariant()), nameof(PublishEmailViaSmtpCommand.IsHtml) }
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var recipient in command.Recipients)
|
||||||
|
form.Add(new StringContent(recipient), nameof(PublishEmailViaSmtpCommand.Recipients));
|
||||||
|
|
||||||
|
using var response = await httpClient.PostAsync("api/Email/smtp", form, cancellationToken);
|
||||||
|
if (response.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
var payload = await response.Content.ReadFromJsonAsync<SendEmailAcceptedResponse>(cancellationToken: cancellationToken)
|
||||||
|
?? throw new HttpRequestException("MessagingService API response body is empty.");
|
||||||
|
|
||||||
|
return payload.Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
var responseText = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||||
|
|
||||||
|
throw new HttpRequestException(
|
||||||
|
$"MessagingService API request failed with status {(int)response.StatusCode} ({response.StatusCode}). Body: {responseText}",
|
||||||
|
null,
|
||||||
|
response.StatusCode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
namespace DigitalData.MessagingService.Client;
|
namespace DigitalData.MessagingService.Client;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Defines the behavior when <see cref="EmailSender.ConnectRabbitMq(Action{RabbitMQ.RabbitMqConfiguration}, OnReconnect)"/> is called
|
/// Defines the behavior when <see cref="EmailSender.ConnectRabbitMq(Action{RabbitMQ.RabbitMqConnectionConfiguration}, OnReconnect)"/> is called
|
||||||
/// while a connection has already been established.
|
/// while a connection has already been established.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public enum OnReconnect
|
public enum OnReconnect
|
||||||
|
|||||||
@@ -0,0 +1,197 @@
|
|||||||
|
using System.Linq.Expressions;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using DigitalData.MessagingService.Application.Common.Dto;
|
||||||
|
using DigitalData.MessagingService.Application.Common.Interfaces;
|
||||||
|
using DigitalData.MessagingService.Application.Common.Interfaces.Repositories;
|
||||||
|
using DigitalData.MessagingService.Application.EmailAccounts.Queries;
|
||||||
|
using DigitalData.MessagingService.Application.EmailSending.Commands;
|
||||||
|
using DigitalData.MessagingService.Client;
|
||||||
|
using DigitalData.MessagingService.Domain.Entities;
|
||||||
|
using DigitalData.MessagingService.Publisher;
|
||||||
|
using DigitalData.MessagingService.RabbitMQ;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace DigitalData.MessagingService.Tests.Integration;
|
||||||
|
|
||||||
|
public sealed class MessagingServiceClientTests : IAsyncDisposable
|
||||||
|
{
|
||||||
|
private const string SenderAddress = "test-flow@digitaldata.works";
|
||||||
|
private const string RecipientAddress = "htek0100@gmail.com";
|
||||||
|
private const string MessagingServiceApiBaseAddress = "http://172.24.12.39:1414";
|
||||||
|
|
||||||
|
private readonly ServiceProvider _serviceProvider;
|
||||||
|
private readonly IMessagingServiceClient _client;
|
||||||
|
private readonly RabbitMqConnectionFactory _factory;
|
||||||
|
|
||||||
|
public MessagingServiceClientTests()
|
||||||
|
{
|
||||||
|
var services = new ServiceCollection();
|
||||||
|
services.AddLogging();
|
||||||
|
|
||||||
|
services.AddMessagingServiceClient(RabbitMqTestConfig.Apply, LoadLuckyPennySoftLicenseKey());
|
||||||
|
services.AddSingleton<IRepository<EmailAccount>>(
|
||||||
|
new InMemoryEmailAccountRepository(
|
||||||
|
[
|
||||||
|
new EmailAccount
|
||||||
|
{
|
||||||
|
Id = 1,
|
||||||
|
Username = SenderAddress,
|
||||||
|
Password = "ddemail108",
|
||||||
|
SmtpServer = "kundencenter.triplew.de",
|
||||||
|
SmtpPort = 465,
|
||||||
|
SmtpUseSsl = true,
|
||||||
|
UseOAuth2 = false
|
||||||
|
}
|
||||||
|
]));
|
||||||
|
|
||||||
|
_serviceProvider = services.BuildServiceProvider();
|
||||||
|
_client = _serviceProvider.GetRequiredService<IMessagingServiceClient>();
|
||||||
|
_factory = _serviceProvider.GetRequiredService<RabbitMqConnectionFactory>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Sends an email through <see cref="IMessagingServiceClient"/> using the real RabbitMQ setup.
|
||||||
|
/// This test intentionally uses manual mailbox verification because the shared queue can be
|
||||||
|
/// consumed by other services during test execution.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task SendAsync_WithDependencyInjectionAndRealBroker_PublishesExpectedMessage()
|
||||||
|
{
|
||||||
|
var subject = $"MessagingServiceClient Integration Test {Guid.NewGuid():N}";
|
||||||
|
|
||||||
|
var command = CreateCommand(subject);
|
||||||
|
|
||||||
|
await _client.SendAsync(command);
|
||||||
|
|
||||||
|
Assert.True(true, "Verify in mailbox.");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task SendAsync_WithHttpClientDependencyInjection_PublishesExpectedMessage()
|
||||||
|
{
|
||||||
|
var services = new ServiceCollection();
|
||||||
|
services.AddLogging();
|
||||||
|
services.AddMessagingServiceHttpClient(client => client.BaseAddress = new Uri(MessagingServiceApiBaseAddress));
|
||||||
|
|
||||||
|
await using var serviceProvider = services.BuildServiceProvider();
|
||||||
|
var client = serviceProvider.GetRequiredService<IMessagingServiceClient>();
|
||||||
|
|
||||||
|
var subject = $"MessagingServiceHttpClient Integration Test {Guid.NewGuid():N}";
|
||||||
|
var command = CreateCommand(subject);
|
||||||
|
|
||||||
|
await Record.ExceptionAsync(() => client.SendAsync(command));
|
||||||
|
|
||||||
|
Assert.True(true, "Verify in mailbox.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static PublishEmailViaSmtpCommand CreateCommand(string subject)
|
||||||
|
{
|
||||||
|
return new PublishEmailViaSmtpCommand
|
||||||
|
{
|
||||||
|
Sender = SenderAddress.ToSender(),
|
||||||
|
Recipients = [RecipientAddress],
|
||||||
|
Subject = subject,
|
||||||
|
Body = "<p>Realistic test mail via MessagingServiceClient.</p>",
|
||||||
|
IsHtml = true
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<SendingEmailEvent?> FindMessageBySubjectAsync(string subject, int maxMessages = 100)
|
||||||
|
{
|
||||||
|
var connection = await _factory.GetDefaultConnectionAsync();
|
||||||
|
await using var channel = await connection.CreateChannelAsync();
|
||||||
|
|
||||||
|
var inspectedTags = new List<ulong>();
|
||||||
|
|
||||||
|
for (var i = 0; i < maxMessages; i++)
|
||||||
|
{
|
||||||
|
var result = await channel.BasicGetAsync(RabbitMqTestConfig.QueueName, autoAck: false);
|
||||||
|
if (result is null)
|
||||||
|
break;
|
||||||
|
|
||||||
|
inspectedTags.Add(result.DeliveryTag);
|
||||||
|
|
||||||
|
var json = Encoding.UTF8.GetString(result.Body.ToArray());
|
||||||
|
var message = JsonSerializer.Deserialize<SendingEmailEvent>(json);
|
||||||
|
if (message?.Mail.Subject == subject)
|
||||||
|
{
|
||||||
|
foreach (var tag in inspectedTags)
|
||||||
|
await channel.BasicNackAsync(tag, multiple: false, requeue: true);
|
||||||
|
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var tag in inspectedTags)
|
||||||
|
await channel.BasicNackAsync(tag, multiple: false, requeue: true);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string LoadLuckyPennySoftLicenseKey()
|
||||||
|
{
|
||||||
|
var appsettingsPath = FindApiAppSettingsPath();
|
||||||
|
using var doc = JsonDocument.Parse(File.ReadAllText(appsettingsPath));
|
||||||
|
|
||||||
|
if (doc.RootElement.TryGetProperty("LuckyPennySoftLicenseKey", out var key) &&
|
||||||
|
key.ValueKind == JsonValueKind.String &&
|
||||||
|
!string.IsNullOrWhiteSpace(key.GetString()))
|
||||||
|
return key.GetString()!;
|
||||||
|
|
||||||
|
throw new InvalidOperationException($"LuckyPennySoftLicenseKey not found in '{appsettingsPath}'.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string FindApiAppSettingsPath()
|
||||||
|
{
|
||||||
|
var current = new DirectoryInfo(AppContext.BaseDirectory);
|
||||||
|
|
||||||
|
while (current is not null)
|
||||||
|
{
|
||||||
|
var candidate = Path.Combine(current.FullName, "src", "presentation", "DigitalData.MessagingService.API", "appsettings.json");
|
||||||
|
if (File.Exists(candidate))
|
||||||
|
return candidate;
|
||||||
|
|
||||||
|
current = current.Parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new FileNotFoundException("Could not locate API appsettings.json from test output directory.");
|
||||||
|
}
|
||||||
|
|
||||||
|
public async ValueTask DisposeAsync()
|
||||||
|
{
|
||||||
|
await _factory.DisposeAsync();
|
||||||
|
await _serviceProvider.DisposeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class InMemoryEmailAccountRepository(IEnumerable<EmailAccount> accounts) : IRepository<EmailAccount>
|
||||||
|
{
|
||||||
|
private readonly List<EmailAccount> _accounts = accounts.ToList();
|
||||||
|
|
||||||
|
public Task<IEnumerable<EmailAccount>> FindAsync(Expression<Func<EmailAccount, bool>> predicate, int? skip = null, int? take = null, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var query = _accounts.AsQueryable().Where(predicate);
|
||||||
|
if (skip.HasValue)
|
||||||
|
query = query.Skip(skip.Value);
|
||||||
|
if (take.HasValue)
|
||||||
|
query = query.Take(take.Value);
|
||||||
|
|
||||||
|
return Task.FromResult<IEnumerable<EmailAccount>>(query.ToList());
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<EmailAccount> CreateAsync<TDto>(TDto dto, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<IEnumerable<EmailAccount>> CreateRangeAsync<TDto>(IEnumerable<TDto> dtos, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<EmailAccount?> GetByIdAsync(int id, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<IEnumerable<EmailAccount>> GetAllAsync(CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<EmailAccount?> FindFirstAsync(Expression<Func<EmailAccount, bool>> predicate, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<EmailAccount?> FindSingleAsync(Expression<Func<EmailAccount, bool>> predicate, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<int> CountAsync(Expression<Func<EmailAccount, bool>>? predicate = null, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<bool> AnyAsync(Expression<Func<EmailAccount, bool>> predicate, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<(EmailAccount Entity, bool Created)> UpsertAsync<TDto>(Expression<Func<EmailAccount, bool>> predicate, TDto dto, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<(EmailAccount Entity, bool Created)> UpsertSingleAsync<TDto>(Expression<Func<EmailAccount, bool>> predicate, TDto dto, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task UpdateSingleAsync<TDto>(Expression<Func<EmailAccount, bool>> predicate, TDto dto, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<int> UpdateAsync<TDto>(Expression<Func<EmailAccount, bool>> predicate, TDto dto, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task DeleteSingleAsync(Expression<Func<EmailAccount, bool>> predicate, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
public Task<int> DeleteAsync(Expression<Func<EmailAccount, bool>> predicate, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -24,7 +24,7 @@ public sealed class SendingEmailPublisherTests : IAsyncDisposable
|
|||||||
{
|
{
|
||||||
var services = new ServiceCollection();
|
var services = new ServiceCollection();
|
||||||
services.AddLogging();
|
services.AddLogging();
|
||||||
services.AddMessagingServicePublisher(cfg => cfg.AddRabbitMqConnectionFactory(RabbitMqTestConfig.Apply));
|
services.AddMessagingServicePublisher(RabbitMqTestConfig.Apply);
|
||||||
|
|
||||||
_serviceProvider = services.BuildServiceProvider();
|
_serviceProvider = services.BuildServiceProvider();
|
||||||
_publisher = _serviceProvider.GetRequiredService<ISendingEmailPublisher>();
|
_publisher = _serviceProvider.GetRequiredService<ISendingEmailPublisher>();
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ internal static class RabbitMqTestConfig
|
|||||||
public const string DlqExchangeName = "emailprofiler.emails.dlq";
|
public const string DlqExchangeName = "emailprofiler.emails.dlq";
|
||||||
public const string DlqRoutingKey = "email.outbox.dlq";
|
public const string DlqRoutingKey = "email.outbox.dlq";
|
||||||
|
|
||||||
public static void Apply(RabbitMqConfiguration cfg)
|
public static void Apply(RabbitMqConnectionConfiguration cfg)
|
||||||
{
|
{
|
||||||
cfg.HostName = HostName;
|
cfg.HostName = HostName;
|
||||||
cfg.Port = Port;
|
cfg.Port = Port;
|
||||||
|
|||||||
@@ -11,12 +11,12 @@ public sealed class EmailSenderUrlParsingTests
|
|||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Applies the same URL-parsing logic used by the URL overload to a fresh
|
/// Applies the same URL-parsing logic used by the URL overload to a fresh
|
||||||
/// <see cref="RabbitMqConfiguration"/> and returns it for assertion.
|
/// <see cref="RabbitMqConnectionConfiguration"/> and returns it for assertion.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static RabbitMqConfiguration ParseUrl(string url, string username, string password)
|
private static RabbitMqConnectionConfiguration ParseUrl(string url, string username, string password)
|
||||||
{
|
{
|
||||||
var uri = new Uri(url);
|
var uri = new Uri(url);
|
||||||
var cfg = new RabbitMqConfiguration();
|
var cfg = new RabbitMqConnectionConfiguration();
|
||||||
|
|
||||||
cfg.HostName = uri.Host;
|
cfg.HostName = uri.Host;
|
||||||
cfg.Port = uri.IsDefaultPort ? 5672 : uri.Port;
|
cfg.Port = uri.IsDefaultPort ? 5672 : uri.Port;
|
||||||
@@ -95,7 +95,7 @@ public sealed class EmailSenderUrlParsingTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void ParseUrl_WithRootPath_DoesNotOverrideVirtualHost()
|
public void ParseUrl_WithRootPath_DoesNotOverrideVirtualHost()
|
||||||
{
|
{
|
||||||
var defaultVHost = new RabbitMqConfiguration().VirtualHost;
|
var defaultVHost = new RabbitMqConnectionConfiguration().VirtualHost;
|
||||||
var cfg = ParseUrl("amqp://broker:5672/", "user", "pass");
|
var cfg = ParseUrl("amqp://broker:5672/", "user", "pass");
|
||||||
|
|
||||||
Assert.Equal(defaultVHost, cfg.VirtualHost);
|
Assert.Equal(defaultVHost, cfg.VirtualHost);
|
||||||
@@ -104,7 +104,7 @@ public sealed class EmailSenderUrlParsingTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void ParseUrl_WithoutPath_DoesNotOverrideVirtualHost()
|
public void ParseUrl_WithoutPath_DoesNotOverrideVirtualHost()
|
||||||
{
|
{
|
||||||
var defaultVHost = new RabbitMqConfiguration().VirtualHost;
|
var defaultVHost = new RabbitMqConnectionConfiguration().VirtualHost;
|
||||||
var cfg = ParseUrl("amqp://broker:5672", "user", "pass");
|
var cfg = ParseUrl("amqp://broker:5672", "user", "pass");
|
||||||
|
|
||||||
Assert.Equal(defaultVHost, cfg.VirtualHost);
|
Assert.Equal(defaultVHost, cfg.VirtualHost);
|
||||||
|
|||||||
Reference in New Issue
Block a user