Compare commits

..

16 Commits

Author SHA1 Message Date
05d16bb32c Refactor and enhance MessagingService client tests
Updated `ToSender` to an extension method for improved usability.
Bumped project version to 3.0.0, reflecting major changes.
Added `MessagingServiceApiBaseAddress` constant for maintainability.
Introduced new test for HTTP client dependency injection.
Refactored command creation into a reusable `CreateCommand` method.
Removed redundant code and improved test structure for clarity.
2026-11-05 10:04:41 +01:00
3e86d4cfe2 feat(client)!: unify client API around IMessagingServiceClient
MessagingServiceClient now implements IMessagingServiceClient and takes a PublishEmailViaSmtpCommand instead of the removed Email record. Add MessagingServiceHttpClient, which posts the same command to the API via IHttpClientFactory.

Replace DependencyInjectionExtensions with a single DependencyInjection entry point that registers exactly one client implementation and throws when a second one is added. It exposes AddMessagingServiceClient for RabbitMQ and AddMessagingServiceHttpClient for the HTTP API, both with an optional license key.

Bump the package to 2.0.0 because the SendAsync signatures and the removed Email type are breaking changes, add Microsoft.Extensions.Http, and update the integration test to exercise the new contract.
2026-11-05 09:45:11 +01:00
c0e0fa3ba1 feat(application): make license key optional
Consumers that use the HTTP client do not pass AutoMapper license data, so the key is now optional and only assigned when supplied. Existing callers keep working unchanged.
2026-11-05 09:45:03 +01:00
4a39e3f92b feat(application): add ToSender helper for email accounts
Adds GetEmailAccountQueryExtensions.ToSender to build a sender query from an email address, and documents its use on PublishEmailViaSmtpCommand.Sender.
2026-11-05 09:44:59 +01:00
f799cdf2c4 feat(application): add IMessagingServiceClient abstraction
The client package will expose two interchangeable implementations (in-process and HTTP), so the contract moves into the application layer where both can depend on it. SendAsync returns the queued message id.
2026-11-05 09:44:56 +01:00
50b92115bb Refactor SendAsync method in MessagingServiceClient
The `SendAsync` method in the `MessagingServiceClient` class has been refactored. It no longer uses the `async` keyword and instead directly returns the `Task` from `sender.Send`. This change simplifies the method by removing the `await` operation, while still maintaining asynchronous behavior through the returned `Task`.
2026-11-04 15:28:51 +01:00
a7d8b3412b Simplify email test verification
Updated the `SendAsync_WithDependencyInjectionAndRealBroker_PublishesExpectedMessage` test in `MessagingServiceClientTests.cs` to use manual mailbox verification. Added XML documentation to explain the change due to potential shared queue consumption by other services. Simplified the test by removing detailed assertions and replacing them with a placeholder assertion to verify manually.
2026-11-04 15:26:59 +01:00
85d1e844b3 Update project version to 2.2.0-beta
Updated the version numbers in the DigitalData.MessagingService.API.csproj file to reflect a new beta release. The `<Version>` has been changed from `2.1.0-beta` to `2.2.0-beta`, and both `<FileVersion>` and `<AssemblyVersion>` have been updated from `2.1.0.0` to `2.2.0.0`. This version increment suggests the introduction of new features, improvements, or bug fixes, and prepares the project for testing or preview before a stable release.
2026-11-04 15:10:01 +01:00
888f01ea95 Add integration tests for MessagingServiceClient
Introduce `MessagingServiceClientTests` to test email sending
via RabbitMQ with dependency injection. Implement methods to
load configuration, manage RabbitMQ messages, and ensure
proper resource disposal. Include an in-memory email account
repository for testing purposes.
2026-11-04 15:09:51 +01:00
034d81f7f6 feat(client): add MessagingServiceClient and dependency injection extensions
Introduce the Email contract and MessagingServiceClient that send mail through the Application layer via MediatR, and add AddMessagingServiceClient overloads for delegate- and IConfiguration-based setup. Remove the empty client DI placeholders.
2026-11-04 14:53:17 +01:00
eed9a0e915 refactor(application)!: accept license key directly in AddMessagingServiceApplication
Remove MessagingServiceApplicationConfiguration and pass the LuckyPennySoft license key as a string. Program.cs now reads the value from configuration and fails fast with a clear error when it is missing.

BREAKING CHANGE: AddMessagingServiceApplication now takes a license key string.
2026-11-04 14:53:09 +01:00
ad2a5240d2 refactor(publisher)!: simplify AddMessagingServicePublisher registration
Replace the MessagingServicePublisherConfiguration builder with plain overloads that accept either a configuration delegate or IConfiguration. Update EmailSender and the publisher integration test to the new API, and mark the static EmailSender obsolete ahead of the new client.

BREAKING CHANGE: AddMessagingServicePublisher no longer accepts a builder configuration delegate.
2026-11-04 14:53:01 +01:00
51d8931dbe refactor(rabbitmq)!: rename RabbitMqConfiguration to RabbitMqConnectionConfiguration
Rename the RabbitMQ options type to make its purpose explicit and update all consumers in the RabbitMQ, Infrastructure, Publisher, Client and test projects. Inline the connection factory registration in the DI extensions instead of the private AddDefaultServices helper.

BREAKING CHANGE: RabbitMqConfiguration is now RabbitMqConnectionConfiguration.
2026-11-04 14:52:52 +01:00
35094529bb Refactor: Remove IServiceCollection dependency
Removed the IServiceCollection dependency and related code from MessagingServiceApplicationConfiguration.cs. This includes the private property `Services`, the boolean field `_luckyPennySoftLicenseKeyAdded`, and the constructor that initialized `Services`. The `EnsureConfigured` method remains, but its functionality may be impacted by these changes.
2026-11-04 11:37:57 +01:00
8cfa803cd3 Refactor DI and update namespace structure
Removed `AddMessagingServiceApplication` method from `DependencyInjection` class, simplifying service configuration. Updated namespaces from `DigitalData.MessagingService.Infrastructure` to `DigitalData.MessagingService.Infrastructure.DependencyInjection` for better organization. Adjusted `Program.cs` to use a lambda for setting `LuckyPennySoftLicenseKey`. Updated `using` directives in `EmailSyncWorker.cs` and `Program.cs` to reflect these changes.
2026-11-02 15:23:32 +01:00
82be3c5a4f Refactor configuration handling
Refactored `MessagingServiceApplicationConfiguration` to simplify the tracking of the LuckyPennySoft license key configuration by replacing the `_configured` tuple with a boolean. Removed email account configuration methods from this class.

Updated `MessagingServiceInfrastructureConfiguration` to introduce a new `_configured` tuple for tracking `RabbitMqConnectionFactory` and `EmailAccounts` configurations. Added methods for configuring email accounts and updated the `EnsureRabbitMqConnectionFactoryAdded` method to include email account checks.

Changed the namespace of `EmailAccountsOptions.cs` to `DigitalData.MessagingService.Infrastructure.Options`.

Modified `Program.cs` to include email account configuration in the infrastructure setup.

Added new files `DependencyInjectionExtensions.cs` and `MessagingServiceConfiguration.cs` as placeholders for future extensions, wrapped in `#if NET` directives.

Removed an `<ItemGroup>` from `DigitalData.MessagingService.Infrastructure.csproj` and updated `DigitalData.MessagingService.Client.csproj` for XML compliance.
2026-11-02 15:23:21 +01:00
31 changed files with 529 additions and 226 deletions

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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>

View File

@@ -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

View File

@@ -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
}

View File

@@ -38,8 +38,4 @@
</Reference> </Reference>
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="Messaging\" />
</ItemGroup>
</Project> </Project>

View File

@@ -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;
}
}

View File

@@ -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

View File

@@ -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,

View File

@@ -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)

View File

@@ -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;

View File

@@ -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();
} }
} }

View File

@@ -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;
}
}

View File

@@ -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;

View File

@@ -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>();
} }
} }
} }

View File

@@ -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

View File

@@ -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 () =>

View File

@@ -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>

View File

@@ -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()

View File

@@ -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

View File

@@ -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-&gt;WithMetadataValue('ReferenceSourceTarget','ProjectReference'))" />
</ItemGroup> </ItemGroup>
</Target> </Target>

View File

@@ -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"/>,

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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();
}
}

View File

@@ -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>();

View File

@@ -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;

View File

@@ -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);