diff --git a/.editorconfig b/.editorconfig
index 1fa8e4eda..a4ab039e2 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -33,7 +33,6 @@ csharp_new_line_before_open_brace=all
csharp_preferred_modifier_order=public, private, protected, internal, new, abstract, virtual, sealed, override, static, readonly, extern, unsafe, volatile, async:suggestion
csharp_space_after_keywords_in_control_flow_statements=true
csharp_style_namespace_declarations = file_scoped:warning
-csharp_style_var_elsewhere=false:suggestion
csharp_style_var_for_built_in_types=false:suggestion
csharp_style_var_when_type_is_apparent=true:suggestion
dotnet_naming_rule.private_constants_rule.severity=warning
diff --git a/samples/src/JustSaying.Sample.Middleware/JustSayingService.cs b/samples/src/JustSaying.Sample.Middleware/JustSayingService.cs
index 09d5b74d2..50d2bcca1 100644
--- a/samples/src/JustSaying.Sample.Middleware/JustSayingService.cs
+++ b/samples/src/JustSaying.Sample.Middleware/JustSayingService.cs
@@ -7,25 +7,14 @@ namespace JustSaying.Sample.Middleware;
///
/// A background service responsible for starting the JustSaying message bus and publisher.
///
-public class JustSayingService : IHostedService
+public class JustSayingService(IMessagingBus bus, IMessagePublisher publisher, ILogger logger) : IHostedService
{
- private readonly IMessagingBus _bus;
- private readonly IMessagePublisher _publisher;
- private readonly ILogger _logger;
-
- public JustSayingService(IMessagingBus bus, IMessagePublisher publisher, ILogger logger)
- {
- _bus = bus;
- _publisher = publisher;
- _logger = logger;
- }
-
public async Task StartAsync(CancellationToken cancellationToken)
{
- await _bus.StartAsync(cancellationToken);
- await _publisher.StartAsync(cancellationToken);
+ await bus.StartAsync(cancellationToken);
+ await publisher.StartAsync(cancellationToken);
- _logger.LogInformation("Message bus and publisher have started successfully");
+ logger.LogInformation("Message bus and publisher have started successfully");
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
diff --git a/samples/src/JustSaying.Sample.Middleware/Middlewares/EchoJustSayingMiddleware.cs b/samples/src/JustSaying.Sample.Middleware/Middlewares/EchoJustSayingMiddleware.cs
index 3a214dec6..3c70a3f3e 100644
--- a/samples/src/JustSaying.Sample.Middleware/Middlewares/EchoJustSayingMiddleware.cs
+++ b/samples/src/JustSaying.Sample.Middleware/Middlewares/EchoJustSayingMiddleware.cs
@@ -1,4 +1,4 @@
-using JustSaying.Messaging.Middleware;
+using JustSaying.Messaging.Middleware;
using Serilog;
namespace JustSaying.Sample.Middleware.Middlewares;
@@ -6,18 +6,11 @@ namespace JustSaying.Sample.Middleware.Middlewares;
///
/// A middleware that will output a log message before and after a message has passed through it.
///
-public class EchoJustSayingMiddleware : MiddlewareBase
+public class EchoJustSayingMiddleware(string name) : MiddlewareBase
{
- private readonly string _name;
-
- public EchoJustSayingMiddleware(string name)
- {
- _name = name;
- }
-
protected override async Task RunInnerAsync(HandleMessageContext context, Func> func, CancellationToken stoppingToken)
{
- Log.Information("[{MiddlewareName}] Starting {Name} for {MessageType}", nameof(EchoJustSayingMiddleware), _name, context.Message.GetType().Name);
+ Log.Information("[{MiddlewareName}] Starting {Name} for {MessageType}", nameof(EchoJustSayingMiddleware), name, context.Message.GetType().Name);
try
{
@@ -25,7 +18,7 @@ protected override async Task RunInnerAsync(HandleMessageContext context,
}
finally
{
- Log.Information("[{MiddlewareName}] Ending {Name} for {MessageType}", nameof(EchoJustSayingMiddleware), _name, context.Message.GetType().Name);
+ Log.Information("[{MiddlewareName}] Ending {Name} for {MessageType}", nameof(EchoJustSayingMiddleware), name, context.Message.GetType().Name);
}
}
}
diff --git a/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/BusService.cs b/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/BusService.cs
index 2736a9c30..4054d5e99 100644
--- a/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/BusService.cs
+++ b/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/BusService.cs
@@ -8,24 +8,13 @@ namespace JustSaying.Sample.Restaurant.KitchenConsole;
/// A background service responsible for starting the bus which listens for
/// messages on the configured queues
///
-public class Subscriber : BackgroundService
+public class Subscriber(IMessagingBus bus, ILogger logger, IMessagePublisher publisher) : BackgroundService
{
- private readonly IMessagingBus _bus;
- private readonly ILogger _logger;
- private readonly IMessagePublisher _publisher;
-
- public Subscriber(IMessagingBus bus, ILogger logger, IMessagePublisher publisher)
- {
- _bus = bus;
- _logger = logger;
- _publisher = publisher;
- }
-
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
- _logger.LogInformation("Kitchen subscriber running");
+ logger.LogInformation("Kitchen subscriber running");
- await _bus.StartAsync(stoppingToken);
- await _publisher.StartAsync(stoppingToken);
+ await bus.StartAsync(stoppingToken);
+ await publisher.StartAsync(stoppingToken);
}
}
diff --git a/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/Handlers/OrderOnItsWayEventHandler.cs b/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/Handlers/OrderOnItsWayEventHandler.cs
index a64465179..1c8101647 100644
--- a/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/Handlers/OrderOnItsWayEventHandler.cs
+++ b/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/Handlers/OrderOnItsWayEventHandler.cs
@@ -6,17 +6,8 @@
namespace JustSaying.Sample.Restaurant.KitchenConsole.Handlers;
-public class OrderOnItsWayEventHandler : IHandlerAsync
+public class OrderOnItsWayEventHandler(IMessagePublisher publisher, ILogger logger) : IHandlerAsync
{
- private readonly IMessagePublisher _publisher;
- private readonly ILogger _logger;
-
- public OrderOnItsWayEventHandler(IMessagePublisher publisher, ILogger logger)
- {
- _publisher = publisher;
- _logger = logger;
- }
-
public async Task Handle(OrderOnItsWayEvent message)
{
await Task.Delay(RandomNumberGenerator.GetInt32(50, 100));
@@ -26,10 +17,10 @@ public async Task Handle(OrderOnItsWayEvent message)
OrderId = message.OrderId
};
- _logger.LogInformation("Order {OrderId} is on its way!", message.OrderId);
+ logger.LogInformation("Order {OrderId} is on its way!", message.OrderId);
- await _publisher.PublishAsync(orderDeliveredEvent);
+ await publisher.PublishAsync(orderDeliveredEvent);
return true;
}
-}
\ No newline at end of file
+}
diff --git a/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/Handlers/OrderPlacedEventHandler.cs b/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/Handlers/OrderPlacedEventHandler.cs
index 18fd28cbc..717c4e36e 100644
--- a/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/Handlers/OrderPlacedEventHandler.cs
+++ b/samples/src/JustSaying.Sample.Restaurant.KitchenConsole/Handlers/OrderPlacedEventHandler.cs
@@ -6,21 +6,12 @@
namespace JustSaying.Sample.Restaurant.KitchenConsole.Handlers;
-public class OrderPlacedEventHandler : IHandlerAsync
+///
+/// Handles messages of type OrderPlacedEvent
+/// Takes a dependency on IMessagePublisher so that further messages can be published
+///
+public class OrderPlacedEventHandler(IMessagePublisher publisher, ILogger logger) : IHandlerAsync
{
- private readonly IMessagePublisher _publisher;
- private readonly ILogger _logger;
-
- ///
- /// Handles messages of type OrderPlacedEvent
- /// Takes a dependency on IMessagePublisher so that further messages can be published
- ///
- public OrderPlacedEventHandler(IMessagePublisher publisher, ILogger log)
- {
- _publisher = publisher;
- _logger = log;
- }
-
public async Task Handle(OrderPlacedEvent message)
{
// Returning true would indicate:
@@ -33,12 +24,12 @@ public async Task Handle(OrderPlacedEvent message)
try
{
- _logger.LogInformation("Order {orderId} for {description} received", message.OrderId, message.Description);
+ logger.LogInformation("Order {orderId} for {description} received", message.OrderId, message.Description);
// This is where you would actually handle the order placement
// Intentionally left empty for the sake of this being a sample application
- _logger.LogInformation("Order {OrderId} ready", message.OrderId);
+ logger.LogInformation("Order {OrderId} ready", message.OrderId);
await Task.Delay(RandomNumberGenerator.GetInt32(50, 100));
@@ -47,13 +38,13 @@ public async Task Handle(OrderPlacedEvent message)
OrderId = message.OrderId
};
- await _publisher.PublishAsync(orderReadyEvent).ConfigureAwait(false);
+ await publisher.PublishAsync(orderReadyEvent).ConfigureAwait(false);
return true;
}
catch (Exception ex)
{
- _logger.LogError(ex, "Failed to handle message for {orderId}", message.OrderId);
+ logger.LogError(ex, "Failed to handle message for {orderId}", message.OrderId);
return false;
}
}
-}
\ No newline at end of file
+}
diff --git a/samples/src/JustSaying.Sample.Restaurant.OrderingApi/BusService.cs b/samples/src/JustSaying.Sample.Restaurant.OrderingApi/BusService.cs
index 80c59618b..1c85277d4 100644
--- a/samples/src/JustSaying.Sample.Restaurant.OrderingApi/BusService.cs
+++ b/samples/src/JustSaying.Sample.Restaurant.OrderingApi/BusService.cs
@@ -6,24 +6,13 @@ namespace JustSaying.Sample.Restaurant.OrderingApi;
/// A background service responsible for starting the bus which listens for
/// messages on the configured queues
///
-public class BusService : BackgroundService
+public class BusService(IMessagingBus bus, ILogger logger, IMessagePublisher publisher) : BackgroundService
{
- private readonly IMessagingBus _bus;
- private readonly ILogger _logger;
- private readonly IMessagePublisher _publisher;
-
- public BusService(IMessagingBus bus, ILogger logger, IMessagePublisher publisher)
- {
- _bus = bus;
- _logger = logger;
- _publisher = publisher;
- }
-
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
- _logger.LogInformation("Ordering API subscriber running");
+ logger.LogInformation("Ordering API subscriber running");
- await _publisher.StartAsync(stoppingToken);
- await _bus.StartAsync(stoppingToken);
+ await publisher.StartAsync(stoppingToken);
+ await bus.StartAsync(stoppingToken);
}
}
diff --git a/samples/src/JustSaying.Sample.Restaurant.OrderingApi/Handlers/OrderDeliveredEventHandler.cs b/samples/src/JustSaying.Sample.Restaurant.OrderingApi/Handlers/OrderDeliveredEventHandler.cs
index 692c90de3..aaf17cf80 100644
--- a/samples/src/JustSaying.Sample.Restaurant.OrderingApi/Handlers/OrderDeliveredEventHandler.cs
+++ b/samples/src/JustSaying.Sample.Restaurant.OrderingApi/Handlers/OrderDeliveredEventHandler.cs
@@ -4,20 +4,13 @@
namespace JustSaying.Sample.Restaurant.OrderingApi.Handlers;
-public class OrderDeliveredEventHandler : IHandlerAsync
+public class OrderDeliveredEventHandler(ILogger logger) : IHandlerAsync
{
- private readonly ILogger _logger;
-
- public OrderDeliveredEventHandler(ILogger logger)
- {
- _logger = logger;
- }
-
public async Task Handle(OrderDeliveredEvent message)
{
await Task.Delay(RandomNumberGenerator.GetInt32(50, 100));
- _logger.LogInformation("Order {OrderId} has been delivered", message.OrderId);
+ logger.LogInformation("Order {OrderId} has been delivered", message.OrderId);
return true;
}
-}
\ No newline at end of file
+}
diff --git a/samples/src/JustSaying.Sample.Restaurant.OrderingApi/Handlers/OrderReadyEventHandler.cs b/samples/src/JustSaying.Sample.Restaurant.OrderingApi/Handlers/OrderReadyEventHandler.cs
index 1503b4c62..d42dbb851 100644
--- a/samples/src/JustSaying.Sample.Restaurant.OrderingApi/Handlers/OrderReadyEventHandler.cs
+++ b/samples/src/JustSaying.Sample.Restaurant.OrderingApi/Handlers/OrderReadyEventHandler.cs
@@ -5,20 +5,11 @@
namespace JustSaying.Sample.Restaurant.OrderingApi.Handlers;
-public class OrderReadyEventHandler : IHandlerAsync
+public class OrderReadyEventHandler(ILogger logger, IMessagePublisher publisher) : IHandlerAsync
{
- private readonly ILogger _logger;
- private readonly IMessagePublisher _publisher;
-
- public OrderReadyEventHandler(ILogger logger, IMessagePublisher publisher)
- {
- _logger = logger;
- _publisher = publisher;
- }
-
public async Task Handle(OrderReadyEvent message)
{
- _logger.LogInformation("Order {orderId} ready", message.OrderId);
+ logger.LogInformation("Order {orderId} ready", message.OrderId);
// This is where you would actually handle the order placement
// Intentionally left empty for the sake of this being a sample application
@@ -30,7 +21,7 @@ public async Task Handle(OrderReadyEvent message)
OrderId = message.OrderId
};
- await _publisher.PublishAsync(orderOnItsWayEvent);
+ await publisher.PublishAsync(orderOnItsWayEvent);
// Returning true would indicate:
// The message was handled successfully
@@ -41,4 +32,4 @@ public async Task Handle(OrderReadyEvent message)
// The message should be moved to the error queue if all retries fail
return true;
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/AwsTools/ErrorQueue.cs b/src/JustSaying/AwsTools/ErrorQueue.cs
index cffdacc4d..64259c31b 100644
--- a/src/JustSaying/AwsTools/ErrorQueue.cs
+++ b/src/JustSaying/AwsTools/ErrorQueue.cs
@@ -11,13 +11,12 @@
namespace JustSaying.AwsTools;
[Obsolete("SqsQueueBase and related classes are not intended for general usage and may be removed in a future major release")]
-public class ErrorQueue : SqsQueueByNameBase
+public class ErrorQueue(
+ RegionEndpoint region,
+ string sourceQueueName,
+ IAmazonSQS client,
+ ILoggerFactory loggerFactory) : SqsQueueByNameBase(region, sourceQueueName + "_error", client, loggerFactory)
{
- public ErrorQueue(RegionEndpoint region, string sourceQueueName, IAmazonSQS client, ILoggerFactory loggerFactory)
- : base(region, sourceQueueName + "_error", client, loggerFactory)
- {
- }
-
protected override Dictionary GetCreateQueueAttributes(SqsBasicConfiguration queueConfig)
{
return new Dictionary
@@ -55,4 +54,4 @@ public override async Task UpdateQueueAttributeAsync(SqsBasicConfiguration queue
protected override bool QueueNeedsUpdating(SqsBasicConfiguration queueConfig)
=> MessageRetentionPeriod != queueConfig.ErrorQueueRetentionPeriod;
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/AwsTools/MessageHandling/Dispatch/MessageDispatcher.cs b/src/JustSaying/AwsTools/MessageHandling/Dispatch/MessageDispatcher.cs
index 97b56c383..83b6f5c27 100644
--- a/src/JustSaying/AwsTools/MessageHandling/Dispatch/MessageDispatcher.cs
+++ b/src/JustSaying/AwsTools/MessageHandling/Dispatch/MessageDispatcher.cs
@@ -93,9 +93,7 @@ await middleware.RunAsync(handleContext, null, cancellationToken)
return (false, null, null);
}
-#pragma warning disable CA1031
catch (Exception ex)
-#pragma warning restore CA1031
{
_logger.LogError(
ex,
diff --git a/src/JustSaying/AwsTools/MessageHandling/Dispatch/MiddlewareMap.cs b/src/JustSaying/AwsTools/MessageHandling/Dispatch/MiddlewareMap.cs
index a412172d1..2b0ee602a 100644
--- a/src/JustSaying/AwsTools/MessageHandling/Dispatch/MiddlewareMap.cs
+++ b/src/JustSaying/AwsTools/MessageHandling/Dispatch/MiddlewareMap.cs
@@ -11,8 +11,7 @@ namespace JustSaying.AwsTools.MessageHandling.Dispatch;
///
public sealed class MiddlewareMap : IInterrogable
{
- private readonly Dictionary<(string queueName, Type type), HandleMessageMiddleware> _middlewares
- = new Dictionary<(string, Type), HandleMessageMiddleware>();
+ private readonly Dictionary<(string queueName, Type type), HandleMessageMiddleware> _middlewares = new();
///
/// Checks if a middleware has been added for a given queue and message type.
@@ -91,4 +90,4 @@ public InterrogationResult Interrogate()
Middlewares = middlewares
});
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/AwsTools/MessageHandling/ForeignTopicArnProvider.cs b/src/JustSaying/AwsTools/MessageHandling/ForeignTopicArnProvider.cs
index 41fce0588..40afe039d 100644
--- a/src/JustSaying/AwsTools/MessageHandling/ForeignTopicArnProvider.cs
+++ b/src/JustSaying/AwsTools/MessageHandling/ForeignTopicArnProvider.cs
@@ -2,15 +2,10 @@
namespace JustSaying.AwsTools.MessageHandling;
-internal class ForeignTopicArnProvider : ITopicArnProvider
+internal class ForeignTopicArnProvider(RegionEndpoint regionEndpoint, string accountId, string topicName) : ITopicArnProvider
{
- private readonly string _arn;
-
- public ForeignTopicArnProvider(RegionEndpoint regionEndpoint, string accountId, string topicName)
- {
- _arn = $"arn:aws:sns:{regionEndpoint.SystemName}:{accountId}:{topicName}";
- }
+ private readonly string _arn = $"arn:aws:sns:{regionEndpoint.SystemName}:{accountId}:{topicName}";
public Task ArnExistsAsync()
{
@@ -22,4 +17,4 @@ public Task GetArnAsync()
{
return Task.FromResult(_arn);
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/AwsTools/MessageHandling/LocalTopicArnProvider.cs b/src/JustSaying/AwsTools/MessageHandling/LocalTopicArnProvider.cs
index cd04b20bb..ffe5a49e5 100644
--- a/src/JustSaying/AwsTools/MessageHandling/LocalTopicArnProvider.cs
+++ b/src/JustSaying/AwsTools/MessageHandling/LocalTopicArnProvider.cs
@@ -24,9 +24,7 @@ private async Task GetArnInternalAsync(string topicName)
_exists = true;
return topic.TopicArn;
}
-#pragma warning disable CA1031
- catch
-#pragma warning restore CA1031
+ catch (Exception)
{
// ignored
}
@@ -43,4 +41,4 @@ public async Task ArnExistsAsync()
_ = await _lazyGetArnAsync.Value.ConfigureAwait(false);
return _exists;
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/AwsTools/MessageHandling/SnsMessagePublisher.cs b/src/JustSaying/AwsTools/MessageHandling/SnsMessagePublisher.cs
index 9953aac06..835773bcf 100644
--- a/src/JustSaying/AwsTools/MessageHandling/SnsMessagePublisher.cs
+++ b/src/JustSaying/AwsTools/MessageHandling/SnsMessagePublisher.cs
@@ -10,15 +10,20 @@
namespace JustSaying.AwsTools.MessageHandling;
-public class SnsMessagePublisher : IMessagePublisher, IInterrogable
+public class SnsMessagePublisher(
+ IAmazonSimpleNotificationService client,
+ IMessageSerializationRegister serializationRegister,
+ ILoggerFactory loggerFactory,
+ IMessageSubjectProvider messageSubjectProvider,
+ Func handleException = null) : IMessagePublisher, IInterrogable
{
- private readonly IMessageSerializationRegister _serializationRegister;
- private readonly IMessageSubjectProvider _messageSubjectProvider;
- private readonly Func _handleException;
+ private readonly IMessageSerializationRegister _serializationRegister = serializationRegister;
+ private readonly IMessageSubjectProvider _messageSubjectProvider = messageSubjectProvider;
+ private readonly Func _handleException = handleException;
public Action MessageResponseLogger { get; set; }
public string Arn { get; internal set; }
- protected IAmazonSimpleNotificationService Client { get; }
- private readonly ILogger _logger;
+ protected IAmazonSimpleNotificationService Client { get; } = client;
+ private readonly ILogger _logger = loggerFactory.CreateLogger("JustSaying.Publish");
public SnsMessagePublisher(
string topicArn,
@@ -32,20 +37,6 @@ public SnsMessagePublisher(
Arn = topicArn;
}
- public SnsMessagePublisher(
- IAmazonSimpleNotificationService client,
- IMessageSerializationRegister serializationRegister,
- ILoggerFactory loggerFactory,
- IMessageSubjectProvider messageSubjectProvider,
- Func handleException = null)
- {
- Client = client;
- _serializationRegister = serializationRegister;
- _logger = loggerFactory.CreateLogger("JustSaying.Publish");
- _handleException = handleException;
- _messageSubjectProvider = messageSubjectProvider;
- }
-
public Task StartAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
@@ -132,7 +123,7 @@ private static MessageAttributeValue BuildMessageAttributeValue(Messaging.Messag
}
var binaryValueStream = value.BinaryValue != null
- ? new MemoryStream(value.BinaryValue.ToArray(), false)
+ ? new MemoryStream([.. value.BinaryValue], false)
: null;
return new MessageAttributeValue
diff --git a/src/JustSaying/AwsTools/MessageHandling/SnsPolicyBuilder.cs b/src/JustSaying/AwsTools/MessageHandling/SnsPolicyBuilder.cs
index bc6de96dd..ddb200e57 100644
--- a/src/JustSaying/AwsTools/MessageHandling/SnsPolicyBuilder.cs
+++ b/src/JustSaying/AwsTools/MessageHandling/SnsPolicyBuilder.cs
@@ -1,5 +1,4 @@
-using System.Text.Json;
-using System.Text.RegularExpressions;
+using System.Text.Json;
using Amazon;
namespace JustSaying.AwsTools.MessageHandling;
diff --git a/src/JustSaying/AwsTools/MessageHandling/SnsTopicByName.cs b/src/JustSaying/AwsTools/MessageHandling/SnsTopicByName.cs
index 4f8e9ab0a..d0cd0dcfa 100644
--- a/src/JustSaying/AwsTools/MessageHandling/SnsTopicByName.cs
+++ b/src/JustSaying/AwsTools/MessageHandling/SnsTopicByName.cs
@@ -8,47 +8,39 @@
namespace JustSaying.AwsTools.MessageHandling;
[Obsolete("SnsTopicByName is not intended for general usage and may be removed in a future major release")]
-public sealed class SnsTopicByName : IInterrogable
+public sealed class SnsTopicByName(
+ string topicName,
+ IAmazonSimpleNotificationService client,
+ ILoggerFactory loggerFactory) : IInterrogable
{
- private readonly IAmazonSimpleNotificationService _client;
- private readonly ILogger _logger;
+ private readonly ILogger _logger = loggerFactory.CreateLogger("JustSaying");
- public string TopicName { get; }
+ public string TopicName { get; } = topicName;
public string Arn { get; private set; }
internal ServerSideEncryption ServerSideEncryption { get; set; }
public IDictionary Tags { get; set; }
- public SnsTopicByName(
- string topicName,
- IAmazonSimpleNotificationService client,
- ILoggerFactory loggerFactory)
- {
- _client = client;
- TopicName = topicName;
- _logger = loggerFactory.CreateLogger("JustSaying");
- }
-
public async Task EnsurePolicyIsUpdatedAsync(IReadOnlyCollection additionalSubscriberAccounts)
{
- if (additionalSubscriberAccounts.Any())
+ if (additionalSubscriberAccounts.Count != 0)
{
var policyDetails = new SnsPolicyDetails
{
AccountIds = additionalSubscriberAccounts,
SourceArn = Arn
};
- await SnsPolicy.SaveAsync(policyDetails, _client).ConfigureAwait(false);
+ await SnsPolicy.SaveAsync(policyDetails, client).ConfigureAwait(false);
}
}
public async Task ApplyTagsAsync(CancellationToken cancellationToken)
{
- if (!Tags.Any())
+ if (Tags.Count < 1)
{
return;
}
- Tag CreateTag(KeyValuePair tag) => new() { Key = tag.Key, Value = tag.Value };
+ static Tag CreateTag(KeyValuePair tag) => new() { Key = tag.Key, Value = tag.Value };
var tagRequest = new TagResourceRequest
{
@@ -56,7 +48,7 @@ public async Task ApplyTagsAsync(CancellationToken cancellationToken)
Tags = Tags.Select(CreateTag).ToList()
};
- await _client.TagResourceAsync(tagRequest, cancellationToken).ConfigureAwait(false);
+ await client.TagResourceAsync(tagRequest, cancellationToken).ConfigureAwait(false);
_logger.LogInformation("Added {TagCount} tags to topic {TopicName}", tagRequest.Tags.Count, TopicName);
}
@@ -69,7 +61,7 @@ public async Task ExistsAsync(CancellationToken cancellationToken)
}
_logger.LogInformation("Checking for existence of the topic '{TopicName}'.", TopicName);
- var topic = await _client.FindTopicAsync(TopicName).ConfigureAwait(false);
+ var topic = await client.FindTopicAsync(TopicName).ConfigureAwait(false);
if (topic != null)
{
@@ -84,7 +76,7 @@ public async Task CreateAsync(CancellationToken cancellationToken)
{
try
{
- var response = await _client.CreateTopicAsync(new CreateTopicRequest(TopicName), cancellationToken)
+ var response = await client.CreateTopicAsync(new CreateTopicRequest(TopicName), cancellationToken)
.ConfigureAwait(false);
if (string.IsNullOrEmpty(response.TopicArn))
@@ -121,7 +113,7 @@ public async Task CreateWithEncryptionAsync(ServerSideEncryption config, Cancell
private async Task ExtractServerSideEncryptionFromTopicAttributes()
{
- var attributesResponse = await _client.GetTopicAttributesAsync(Arn).ConfigureAwait(false);
+ var attributesResponse = await client.GetTopicAttributesAsync(Arn).ConfigureAwait(false);
if (!attributesResponse.Attributes.TryGetValue(
JustSayingConstants.AttributeEncryptionKeyId,
@@ -147,7 +139,7 @@ private async Task EnsureServerSideEncryptionIsUpdatedAsync(ServerSideEncryption
AttributeValue = config?.KmsMasterKeyId ?? string.Empty
};
- var response = await _client.SetTopicAttributesAsync(request).ConfigureAwait(false);
+ var response = await client.SetTopicAttributesAsync(request).ConfigureAwait(false);
if (response.HttpStatusCode == HttpStatusCode.OK)
{
@@ -190,4 +182,4 @@ public InterrogationResult Interrogate()
});
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/AwsTools/MessageHandling/SqsMessagePublisher.cs b/src/JustSaying/AwsTools/MessageHandling/SqsMessagePublisher.cs
index 1fee4ed9c..dc6a77337 100644
--- a/src/JustSaying/AwsTools/MessageHandling/SqsMessagePublisher.cs
+++ b/src/JustSaying/AwsTools/MessageHandling/SqsMessagePublisher.cs
@@ -9,11 +9,12 @@
namespace JustSaying.AwsTools.MessageHandling;
-public class SqsMessagePublisher : IMessagePublisher
+public class SqsMessagePublisher(
+ IAmazonSQS client,
+ IMessageSerializationRegister serializationRegister,
+ ILoggerFactory loggerFactory) : IMessagePublisher
{
- private readonly IAmazonSQS _client;
- private readonly IMessageSerializationRegister _serializationRegister;
- private readonly ILogger _logger;
+ private readonly ILogger _logger = loggerFactory.CreateLogger("JustSaying.Publish");
public Action MessageResponseLogger { get; set; }
public Uri QueueUrl { get; internal set; }
@@ -27,16 +28,6 @@ public SqsMessagePublisher(
QueueUrl = queueUrl;
}
- public SqsMessagePublisher(
- IAmazonSQS client,
- IMessageSerializationRegister serializationRegister,
- ILoggerFactory loggerFactory)
- {
- _client = client;
- _serializationRegister = serializationRegister;
- _logger = loggerFactory.CreateLogger("JustSaying.Publish");
- }
-
public Task StartAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
@@ -53,7 +44,7 @@ public async Task PublishAsync(Message message, PublishMetadata metadata, Cancel
SendMessageResponse response;
try
{
- response = await _client.SendMessageAsync(request, cancellationToken).ConfigureAwait(false);
+ response = await client.SendMessageAsync(request, cancellationToken).ConfigureAwait(false);
}
catch (AmazonServiceException ex)
{
@@ -103,7 +94,7 @@ private SendMessageRequest BuildSendMessageRequest(Message message, PublishMetad
return request;
}
- public string GetMessageInContext(Message message) => _serializationRegister.Serialize(message, serializeForSnsPublishing: false);
+ public string GetMessageInContext(Message message) => serializationRegister.Serialize(message, serializeForSnsPublishing: false);
public InterrogationResult Interrogate()
{
diff --git a/src/JustSaying/AwsTools/MessageHandling/SqsQueueByName.cs b/src/JustSaying/AwsTools/MessageHandling/SqsQueueByName.cs
index 8a6dc6e1b..d73ab35ad 100644
--- a/src/JustSaying/AwsTools/MessageHandling/SqsQueueByName.cs
+++ b/src/JustSaying/AwsTools/MessageHandling/SqsQueueByName.cs
@@ -10,18 +10,14 @@
namespace JustSaying.AwsTools.MessageHandling;
[Obsolete("SqsQueueBase and related classes are not intended for general usage and may be removed in a future major release")]
-public class SqsQueueByName : SqsQueueByNameBase
+public class SqsQueueByName(
+ RegionEndpoint region,
+ string queueName,
+ IAmazonSQS client,
+ int retryCountBeforeSendingToErrorQueue,
+ ILoggerFactory loggerFactory) : SqsQueueByNameBase(region, queueName, client, loggerFactory)
{
- private readonly int _retryCountBeforeSendingToErrorQueue;
-
- internal ErrorQueue ErrorQueue { get; }
-
- public SqsQueueByName(RegionEndpoint region, string queueName, IAmazonSQS client, int retryCountBeforeSendingToErrorQueue, ILoggerFactory loggerFactory)
- : base(region, queueName, client, loggerFactory)
- {
- _retryCountBeforeSendingToErrorQueue = retryCountBeforeSendingToErrorQueue;
- ErrorQueue = new ErrorQueue(region, queueName, client, loggerFactory);
- }
+ internal ErrorQueue ErrorQueue { get; } = new ErrorQueue(region, queueName, client, loggerFactory);
public override async Task CreateAsync(SqsBasicConfiguration queueConfig, int attempt = 0, CancellationToken cancellationToken = default)
{
@@ -135,7 +131,7 @@ await UpdateRedrivePolicyAsync(
private async Task ApplyTagsAsync(ISqsQueue queue, Dictionary tags, CancellationToken cancellationToken)
{
- if (tags == null || !tags.Any())
+ if (tags == null || tags.Count == 0)
{
return;
}
@@ -157,7 +153,7 @@ protected override Dictionary GetCreateQueueAttributes(SqsBasicC
if (NeedErrorQueue(queueConfig))
{
- policy.Add(JustSayingConstants.AttributeRedrivePolicy, new RedrivePolicy(_retryCountBeforeSendingToErrorQueue, ErrorQueue.Arn).ToString());
+ policy.Add(JustSayingConstants.AttributeRedrivePolicy, new RedrivePolicy(retryCountBeforeSendingToErrorQueue, ErrorQueue.Arn).ToString());
}
if (queueConfig.ServerSideEncryption != null)
diff --git a/src/JustSaying/AwsTools/MessageHandling/SqsQueueByNameBase.cs b/src/JustSaying/AwsTools/MessageHandling/SqsQueueByNameBase.cs
index e6ea17489..664c96d0c 100644
--- a/src/JustSaying/AwsTools/MessageHandling/SqsQueueByNameBase.cs
+++ b/src/JustSaying/AwsTools/MessageHandling/SqsQueueByNameBase.cs
@@ -77,7 +77,7 @@ public virtual async Task ExistsAsync(CancellationToken cancellationToken)
Uri = new Uri(result.QueueUrl);
- await SetQueuePropertiesAsync(cancellationToken).ConfigureAwait(false);
+ await SetQueuePropertiesAsync().ConfigureAwait(false);
return true;
}
@@ -96,7 +96,7 @@ public virtual async Task CreateAsync(SqsBasicConfiguration queueConfig, i
{
Uri = new Uri(queueResponse.QueueUrl);
await Client.SetQueueAttributesAsync(queueResponse.QueueUrl, GetCreateQueueAttributes(queueConfig), cancellationToken).ConfigureAwait(false);
- await SetQueuePropertiesAsync(cancellationToken).ConfigureAwait(false);
+ await SetQueuePropertiesAsync().ConfigureAwait(false);
Logger.LogInformation("Created queue '{QueueName}' with ARN '{Arn}'.", QueueName, Arn);
return true;
@@ -126,7 +126,7 @@ public virtual async Task CreateAsync(SqsBasicConfiguration queueConfig, i
maxAttempts);
await Task.Delay(CreateRetryDelay, cancellationToken).ConfigureAwait(false);
- await CreateAsync(queueConfig, attempt + 1).ConfigureAwait(false);
+ _ = await CreateAsync(queueConfig, attempt + 1).ConfigureAwait(false);
}
else
{
@@ -155,10 +155,10 @@ public virtual async Task DeleteAsync(CancellationToken cancellationToken)
}
}
- private async Task SetQueuePropertiesAsync(CancellationToken cancellationToken)
+ private async Task SetQueuePropertiesAsync()
{
- var keys = new[]
- {
+ string[] keys =
+ [
JustSayingConstants.AttributeArn,
JustSayingConstants.AttributeRedrivePolicy,
JustSayingConstants.AttributePolicy,
@@ -167,8 +167,8 @@ private async Task SetQueuePropertiesAsync(CancellationToken cancellationToken)
JustSayingConstants.AttributeDeliveryDelay,
JustSayingConstants.AttributeEncryptionKeyId,
JustSayingConstants.AttributeEncryptionKeyReusePeriodSecondId
- };
- var attributes = await GetAttrsAsync(keys).ConfigureAwait(false);
+ ];
+ var attributes = await GetAttributesAsync(keys).ConfigureAwait(false);
Arn = attributes.QueueARN;
MessageRetentionPeriod = TimeSpan.FromSeconds(attributes.MessageRetentionPeriod);
_visibilityTimeout = TimeSpan.FromSeconds(attributes.VisibilityTimeout);
@@ -178,7 +178,7 @@ private async Task SetQueuePropertiesAsync(CancellationToken cancellationToken)
ServerSideEncryption = ExtractServerSideEncryptionFromQueueAttributes(attributes.Attributes);
}
- private async Task GetAttrsAsync(IEnumerable attrKeys)
+ private async Task GetAttributesAsync(IEnumerable attrKeys)
{
var request = new GetQueueAttributesRequest
{
diff --git a/src/JustSaying/AwsTools/QueueCreation/AmazonQueueCreator.cs b/src/JustSaying/AwsTools/QueueCreation/AmazonQueueCreator.cs
index 3b09ec4d2..69c773c55 100644
--- a/src/JustSaying/AwsTools/QueueCreation/AmazonQueueCreator.cs
+++ b/src/JustSaying/AwsTools/QueueCreation/AmazonQueueCreator.cs
@@ -6,26 +6,15 @@
namespace JustSaying.AwsTools.QueueCreation;
-public class AmazonQueueCreator : IVerifyAmazonQueues
+public class AmazonQueueCreator(IAwsClientFactoryProxy awsClientFactory, ILoggerFactory loggerFactory) : IVerifyAmazonQueues
{
- private readonly IAwsClientFactoryProxy _awsClientFactory;
- private readonly ILoggerFactory _loggerFactory;
-
- private const string EmptyFilterPolicy = "{}";
-
- public AmazonQueueCreator(IAwsClientFactoryProxy awsClientFactory, ILoggerFactory loggerFactory)
- {
- _awsClientFactory = awsClientFactory;
- _loggerFactory = loggerFactory;
- }
-
public QueueWithAsyncStartup EnsureTopicExistsWithQueueSubscribed(
string region,
SqsReadConfiguration queueConfig)
{
var regionEndpoint = RegionEndpoint.GetBySystemName(region);
- var sqsClient = _awsClientFactory.GetAwsClientFactory().GetSqsClient(regionEndpoint);
- var snsClient = _awsClientFactory.GetAwsClientFactory().GetSnsClient(regionEndpoint);
+ var sqsClient = awsClientFactory.GetAwsClientFactory().GetSqsClient(regionEndpoint);
+ var snsClient = awsClientFactory.GetAwsClientFactory().GetSnsClient(regionEndpoint);
var queueWithStartup = EnsureQueueExists(region, queueConfig);
@@ -49,7 +38,7 @@ await SubscribeQueueAndApplyFilterPolicyAsync(snsClient,
else
{
#pragma warning disable 618
- var eventTopic = new SnsTopicByName(queueConfig.PublishEndpoint, snsClient, _loggerFactory);
+ var eventTopic = new SnsTopicByName(queueConfig.PublishEndpoint, snsClient, loggerFactory);
#pragma warning restore 618
await eventTopic.CreateAsync(cancellationToken).ConfigureAwait(false);
@@ -84,14 +73,14 @@ public QueueWithAsyncStartup EnsureQueueExists(
SqsReadConfiguration queueConfig)
{
var regionEndpoint = RegionEndpoint.GetBySystemName(region);
- var sqsClient = _awsClientFactory.GetAwsClientFactory().GetSqsClient(regionEndpoint);
+ var sqsClient = awsClientFactory.GetAwsClientFactory().GetSqsClient(regionEndpoint);
#pragma warning disable 618
var queue = new SqsQueueByName(regionEndpoint,
queueConfig.QueueName,
sqsClient,
queueConfig.RetryCountBeforeSendingToErrorQueue,
- _loggerFactory);
+ loggerFactory);
#pragma warning restore 618
var startupTask = new Func(ct => queue.EnsureQueueAndErrorQueueExistAndAllAttributesAreUpdatedAsync(
@@ -117,9 +106,9 @@ private static async Task SubscribeQueueAndApplyFilterPolicyAsync(
.ConfigureAwait(false);
var actualFilterPolicy =
- string.IsNullOrWhiteSpace(filterPolicy) ? EmptyFilterPolicy : filterPolicy;
+ string.IsNullOrWhiteSpace(filterPolicy) ? "{}" : filterPolicy;
await amazonSimpleNotificationService
.SetSubscriptionAttributesAsync(subscriptionArn, "FilterPolicy", actualFilterPolicy)
.ConfigureAwait(false);
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Extensions/AmazonSqsClientExtensions.cs b/src/JustSaying/Extensions/AmazonSqsClientExtensions.cs
index 780579090..c9a086227 100644
--- a/src/JustSaying/Extensions/AmazonSqsClientExtensions.cs
+++ b/src/JustSaying/Extensions/AmazonSqsClientExtensions.cs
@@ -23,7 +23,7 @@ public static async Task> ReceiveMessagesAsync(this IAmazonSQS cl
var result = await client.ReceiveMessageAsync(new ReceiveMessageRequest(queueUrl)
{
- AttributeNames = attributesToLoad.ToList(),
+ AttributeNames = [.. attributesToLoad],
WaitTimeSeconds = secondsWaitTime,
MaxNumberOfMessages = maxNumOfMessages
},
@@ -32,4 +32,4 @@ public static async Task> ReceiveMessagesAsync(this IAmazonSQS cl
if (result?.Messages != null) return result.Messages;
return Array.Empty();
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Extensions/TypeExtensions.cs b/src/JustSaying/Extensions/TypeExtensions.cs
index 0927fc3ed..aa298e139 100644
--- a/src/JustSaying/Extensions/TypeExtensions.cs
+++ b/src/JustSaying/Extensions/TypeExtensions.cs
@@ -1,6 +1,6 @@
namespace JustSaying.Extensions;
-static class TypeExtensions
+internal static class TypeExtensions
{
public static string ToSimpleName(this Type type) =>
type.ToString().Replace($"{type.Namespace}.", "");
diff --git a/src/JustSaying/Fluent/AwsClientFactoryBuilder.cs b/src/JustSaying/Fluent/AwsClientFactoryBuilder.cs
index 7a5c85615..cb39a0568 100644
--- a/src/JustSaying/Fluent/AwsClientFactoryBuilder.cs
+++ b/src/JustSaying/Fluent/AwsClientFactoryBuilder.cs
@@ -146,9 +146,7 @@ public AwsClientFactoryBuilder WithSessionCredentials(string accessKeyId, string
///
/// is not an absolute URI.
///
-#pragma warning disable CA1054 // Uri parameters should not be strings
public AwsClientFactoryBuilder WithServiceUrl(string url)
-#pragma warning restore CA1054 // Uri parameters should not be strings
{
if (url == null)
{
@@ -187,4 +185,4 @@ public AwsClientFactoryBuilder WithServiceUri(Uri uri)
return this;
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Fluent/MessagingConfigurationBuilder.cs b/src/JustSaying/Fluent/MessagingConfigurationBuilder.cs
index 4374cc2ae..317261de3 100644
--- a/src/JustSaying/Fluent/MessagingConfigurationBuilder.cs
+++ b/src/JustSaying/Fluent/MessagingConfigurationBuilder.cs
@@ -114,10 +114,7 @@ public MessagingConfigurationBuilder WithAdditionalSubscriberAccount(string acco
throw new ArgumentNullException(nameof(accountId));
}
- if (AdditionalSubscriberAccounts == null)
- {
- AdditionalSubscriberAccounts = new List();
- }
+ AdditionalSubscriberAccounts ??= new List();
AdditionalSubscriberAccounts.Add(accountId);
return this;
@@ -334,4 +331,4 @@ public IMessagingConfig Build()
return config;
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Fluent/PublicationsBuilder.cs b/src/JustSaying/Fluent/PublicationsBuilder.cs
index 39a4e363e..83139211d 100644
--- a/src/JustSaying/Fluent/PublicationsBuilder.cs
+++ b/src/JustSaying/Fluent/PublicationsBuilder.cs
@@ -26,7 +26,7 @@ internal PublicationsBuilder(MessagingBusBuilder parent)
///
/// Gets the configured publication builders.
///
- private IList> Publications { get; } = new List>();
+ private List> Publications { get; } = [];
///
/// Configures a publisher for a queue.
@@ -204,4 +204,4 @@ internal void Configure(JustSayingBus bus, IAwsClientFactoryProxy proxy, ILogger
builder.Configure(bus, proxy, loggerFactory);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Fluent/PublishConfig/DynamicMessagePublisher.cs b/src/JustSaying/Fluent/PublishConfig/DynamicMessagePublisher.cs
index efdfdf39e..c37616e04 100644
--- a/src/JustSaying/Fluent/PublishConfig/DynamicMessagePublisher.cs
+++ b/src/JustSaying/Fluent/PublishConfig/DynamicMessagePublisher.cs
@@ -6,21 +6,14 @@
namespace JustSaying.Fluent;
-internal sealed class DynamicMessagePublisher : IMessagePublisher
+internal sealed class DynamicMessagePublisher(
+ Func topicNameCustomizer,
+ Func staticConfigBuilder,
+ ILoggerFactory loggerFactory) : IMessagePublisher
{
private readonly ConcurrentDictionary _publisherCache = new();
- private readonly Func _topicNameCustomizer;
- private readonly Func _staticConfigBuilder;
-
private readonly ConcurrentDictionary _topicCreationLocks = new();
- private readonly ILogger _logger;
-
- public DynamicMessagePublisher(Func topicNameCustomizer, Func staticConfigBuilder, ILoggerFactory loggerFactory)
- {
- _topicNameCustomizer = topicNameCustomizer;
- _staticConfigBuilder = staticConfigBuilder;
- _logger = loggerFactory.CreateLogger();
- }
+ private readonly ILogger _logger = loggerFactory.CreateLogger();
public InterrogationResult Interrogate()
{
@@ -40,7 +33,7 @@ public Task StartAsync(CancellationToken stoppingToken)
public async Task PublishAsync(Message message, PublishMetadata metadata, CancellationToken cancellationToken)
{
- var topicName = _topicNameCustomizer(message);
+ var topicName = topicNameCustomizer(message);
if (_publisherCache.TryGetValue(topicName, out var publisher))
{
await publisher.PublishAsync(message, metadata, cancellationToken).ConfigureAwait(false);
@@ -59,7 +52,7 @@ public async Task PublishAsync(Message message, PublishMetadata metadata, Cancel
}
_logger.LogDebug("Lock acquired to initialize topic {TopicName}", topicName);
- var config = _staticConfigBuilder(topicName);
+ var config = staticConfigBuilder(topicName);
_logger.LogDebug("Executing startup task for topic {TopicName}", topicName);
await config.StartupTask(cancellationToken).ConfigureAwait(false);
diff --git a/src/JustSaying/Fluent/PublishConfig/DynamicPublicationConfiguration.cs b/src/JustSaying/Fluent/PublishConfig/DynamicPublicationConfiguration.cs
index b41d1cc43..e55c6bf41 100644
--- a/src/JustSaying/Fluent/PublishConfig/DynamicPublicationConfiguration.cs
+++ b/src/JustSaying/Fluent/PublishConfig/DynamicPublicationConfiguration.cs
@@ -4,15 +4,10 @@
namespace JustSaying.Fluent;
-internal sealed class DynamicPublicationConfiguration : ITopicPublisher
+internal sealed class DynamicPublicationConfiguration(IMessagePublisher publisher) : ITopicPublisher
{
- public DynamicPublicationConfiguration(IMessagePublisher publisher)
- {
- Publisher = publisher;
- }
-
public Func StartupTask => _ => Task.CompletedTask;
- public IMessagePublisher Publisher { get; }
+ public IMessagePublisher Publisher { get; } = publisher;
public static DynamicPublicationConfiguration Build(
Func topicNameCustomizer,
diff --git a/src/JustSaying/Fluent/PublishConfig/StaticPublicationConfiguration.cs b/src/JustSaying/Fluent/PublishConfig/StaticPublicationConfiguration.cs
index 29e12dab2..f7b8410fb 100644
--- a/src/JustSaying/Fluent/PublishConfig/StaticPublicationConfiguration.cs
+++ b/src/JustSaying/Fluent/PublishConfig/StaticPublicationConfiguration.cs
@@ -8,18 +8,12 @@
namespace JustSaying.Fluent;
-internal sealed class StaticPublicationConfiguration : ITopicPublisher
+internal sealed class StaticPublicationConfiguration(
+ Func startupTask,
+ IMessagePublisher publisher) : ITopicPublisher
{
- public Func StartupTask { get; }
- public IMessagePublisher Publisher { get; }
-
- public StaticPublicationConfiguration(
- Func startupTask,
- IMessagePublisher publisher)
- {
- StartupTask = startupTask;
- Publisher = publisher;
- }
+ public Func StartupTask { get; } = startupTask;
+ public IMessagePublisher Publisher { get; } = publisher;
public static StaticPublicationConfiguration Build(
string topicName,
diff --git a/src/JustSaying/Fluent/QueueAddressConfiguration.cs b/src/JustSaying/Fluent/QueueAddressConfiguration.cs
index 9f20fc7e9..b0a4d28d7 100644
--- a/src/JustSaying/Fluent/QueueAddressConfiguration.cs
+++ b/src/JustSaying/Fluent/QueueAddressConfiguration.cs
@@ -9,5 +9,6 @@ public sealed class QueueAddressConfiguration
public void Validate()
{
+ // TODO
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Fluent/QueueAddressSubscriptionBuilder`1.cs b/src/JustSaying/Fluent/QueueAddressSubscriptionBuilder`1.cs
index eb1687113..2e266accc 100644
--- a/src/JustSaying/Fluent/QueueAddressSubscriptionBuilder`1.cs
+++ b/src/JustSaying/Fluent/QueueAddressSubscriptionBuilder`1.cs
@@ -87,13 +87,8 @@ void ISubscriptionBuilder.Configure(
typeof(T), queue.QueueName);
var resolutionContext = new HandlerResolutionContext(queue.QueueName);
- var proposedHandler = handlerResolver.ResolveHandler(resolutionContext);
- if (proposedHandler == null)
- {
- throw new HandlerNotRegisteredWithContainerException(
+ var proposedHandler = handlerResolver.ResolveHandler(resolutionContext) ?? throw new HandlerNotRegisteredWithContainerException(
$"There is no handler for '{typeof(T)}' messages.");
- }
-
var middlewareBuilder = new HandlerMiddlewareBuilder(handlerResolver, serviceResolver);
var handlerMiddleware = middlewareBuilder
.Configure(MiddlewareConfiguration ?? (b => b.UseDefaults(proposedHandler.GetType())))
@@ -105,4 +100,4 @@ void ISubscriptionBuilder.Configure(
"Added a message handler for message type for '{MessageType}' on queue '{QueueName}'",
typeof(T), queue.QueueName);
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Fluent/QueuePublicationBuilder`1.cs b/src/JustSaying/Fluent/QueuePublicationBuilder`1.cs
index 9d05f81f8..8bc4eacab 100644
--- a/src/JustSaying/Fluent/QueuePublicationBuilder`1.cs
+++ b/src/JustSaying/Fluent/QueuePublicationBuilder`1.cs
@@ -78,7 +78,7 @@ public QueuePublicationBuilder WithWriteConfiguration(Action
public QueuePublicationBuilder WithName(string queueName)
{
- return this.WithWriteConfiguration(r => r.WithQueueName(queueName));
+ return WithWriteConfiguration(r => r.WithQueueName(queueName));
}
///
@@ -140,4 +140,4 @@ async Task StartupTask(CancellationToken cancellationToken)
typeof(T),
writeConfiguration.QueueName);
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Fluent/QueueSubscriptionBuilder`1.cs b/src/JustSaying/Fluent/QueueSubscriptionBuilder`1.cs
index 01e42f823..84cb978e6 100644
--- a/src/JustSaying/Fluent/QueueSubscriptionBuilder`1.cs
+++ b/src/JustSaying/Fluent/QueueSubscriptionBuilder`1.cs
@@ -192,13 +192,8 @@ void ISubscriptionBuilder.Configure(
subscriptionConfig.QueueName);
var resolutionContext = new HandlerResolutionContext(subscriptionConfig.QueueName);
- var proposedHandler = handlerResolver.ResolveHandler(resolutionContext);
- if (proposedHandler == null)
- {
- throw new HandlerNotRegisteredWithContainerException(
+ var proposedHandler = handlerResolver.ResolveHandler(resolutionContext) ?? throw new HandlerNotRegisteredWithContainerException(
$"There is no handler for '{typeof(T)}' messages.");
- }
-
var middlewareBuilder = new HandlerMiddlewareBuilder(handlerResolver, serviceResolver);
var handlerMiddleware = middlewareBuilder
.Configure(MiddlewareConfiguration ?? (b => b.UseDefaults(proposedHandler.GetType())))
diff --git a/src/JustSaying/Fluent/ServiceResolver/CompoundServiceResolver.cs b/src/JustSaying/Fluent/ServiceResolver/CompoundServiceResolver.cs
index 28ed6d53f..279b09bdc 100644
--- a/src/JustSaying/Fluent/ServiceResolver/CompoundServiceResolver.cs
+++ b/src/JustSaying/Fluent/ServiceResolver/CompoundServiceResolver.cs
@@ -1,25 +1,16 @@
namespace JustSaying.Fluent.ServiceResolver;
-internal class CompoundServiceResolver : IServiceResolver
+internal class CompoundServiceResolver(ServiceBuilderServiceResolver serviceBuilderResolver, IServiceResolver serviceResolver) : IServiceResolver
{
- private readonly ServiceBuilderServiceResolver _serviceBuilderResolver;
- private readonly IServiceResolver _serviceResolver;
-
- public CompoundServiceResolver(ServiceBuilderServiceResolver serviceBuilderResolver, IServiceResolver serviceResolver)
- {
- _serviceBuilderResolver = serviceBuilderResolver;
- _serviceResolver = serviceResolver;
- }
-
public T ResolveService() where T : class
{
- return _serviceBuilderResolver.ResolveOptionalService() ??
- _serviceResolver.ResolveService();
+ return serviceBuilderResolver.ResolveOptionalService() ??
+ serviceResolver.ResolveService();
}
public T ResolveOptionalService() where T : class
{
- return _serviceBuilderResolver.ResolveOptionalService() ??
- _serviceResolver.ResolveOptionalService();
+ return serviceBuilderResolver.ResolveOptionalService() ??
+ serviceResolver.ResolveOptionalService();
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Fluent/ServiceResolver/ServiceBuilderServiceResolver.cs b/src/JustSaying/Fluent/ServiceResolver/ServiceBuilderServiceResolver.cs
index 840759ff1..df06550f2 100644
--- a/src/JustSaying/Fluent/ServiceResolver/ServiceBuilderServiceResolver.cs
+++ b/src/JustSaying/Fluent/ServiceResolver/ServiceBuilderServiceResolver.cs
@@ -7,19 +7,12 @@
namespace JustSaying.Fluent;
-internal class ServiceBuilderServiceResolver : IServiceResolver
+internal class ServiceBuilderServiceResolver(ServicesBuilder builder) : IServiceResolver
{
- private readonly ServicesBuilder _builder;
-
private readonly ConcurrentDictionary _serviceLookup = new();
private bool _built = false;
- public ServiceBuilderServiceResolver(ServicesBuilder builder)
- {
- _builder = builder;
- }
-
public T ResolveService() where T : class
{
return ResolveOptionalService() ??
@@ -29,34 +22,34 @@ public T ResolveService() where T : class
private void Build()
{
- if (_builder.HandlerResolver != null)
+ if (builder.HandlerResolver != null)
{
- _serviceLookup[typeof(IHandlerResolver)] = _builder.HandlerResolver();
+ _serviceLookup[typeof(IHandlerResolver)] = builder.HandlerResolver();
}
- if (_builder.LoggerFactory != null)
+ if (builder.LoggerFactory != null)
{
- _serviceLookup[typeof(ILoggerFactory)] = _builder.LoggerFactory();
+ _serviceLookup[typeof(ILoggerFactory)] = builder.LoggerFactory();
}
- if (_builder.BusBuilder.ClientFactoryBuilder != null)
+ if (builder.BusBuilder.ClientFactoryBuilder != null)
{
- _serviceLookup[typeof(IAwsClientFactory)] = _builder.BusBuilder.ClientFactoryBuilder.Build();
+ _serviceLookup[typeof(IAwsClientFactory)] = builder.BusBuilder.ClientFactoryBuilder.Build();
}
- if (_builder.MessageMonitoring != null)
+ if (builder.MessageMonitoring != null)
{
- _serviceLookup[typeof(IMessageMonitor)] = _builder.MessageMonitoring();
+ _serviceLookup[typeof(IMessageMonitor)] = builder.MessageMonitoring();
}
- if (_builder.SerializationRegister != null)
+ if (builder.SerializationRegister != null)
{
- _serviceLookup[typeof(IMessageSerializationRegister)] = _builder.SerializationRegister();
+ _serviceLookup[typeof(IMessageSerializationRegister)] = builder.SerializationRegister();
}
- if (_builder.MessageContextAccessor != null)
+ if (builder.MessageContextAccessor != null)
{
- _serviceLookup[typeof(IMessageContextAccessor)] = _builder.MessageContextAccessor();
+ _serviceLookup[typeof(IMessageContextAccessor)] = builder.MessageContextAccessor();
}
_built = true;
@@ -74,4 +67,4 @@ public T ResolveOptionalService() where T : class
return null;
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Fluent/SqsConfigurationBuilder.cs b/src/JustSaying/Fluent/SqsConfigurationBuilder.cs
index 2afc57cd8..6d2653df8 100644
--- a/src/JustSaying/Fluent/SqsConfigurationBuilder.cs
+++ b/src/JustSaying/Fluent/SqsConfigurationBuilder.cs
@@ -55,17 +55,8 @@ internal SqsConfigurationBuilder()
///
public TBuilder WithEncryption(string masterKeyId)
{
- if (masterKeyId == null)
- {
- throw new ArgumentNullException(nameof(masterKeyId));
- }
-
- if (Encryption == null)
- {
- Encryption = new ServerSideEncryption();
- }
-
- Encryption.KmsMasterKeyId = masterKeyId;
+ Encryption ??= new ServerSideEncryption();
+ Encryption.KmsMasterKeyId = masterKeyId ?? throw new ArgumentNullException(nameof(masterKeyId));
return Self;
}
diff --git a/src/JustSaying/Fluent/SubscriptionsBuilder.cs b/src/JustSaying/Fluent/SubscriptionsBuilder.cs
index c180347b6..8cb0df0e1 100644
--- a/src/JustSaying/Fluent/SubscriptionsBuilder.cs
+++ b/src/JustSaying/Fluent/SubscriptionsBuilder.cs
@@ -26,15 +26,14 @@ internal SubscriptionsBuilder(MessagingBusBuilder parent)
///
internal MessagingBusBuilder Parent { get; }
- internal SubscriptionGroupSettingsBuilder Defaults = new SubscriptionGroupSettingsBuilder();
+ internal SubscriptionGroupSettingsBuilder Defaults = new();
///
/// Gets the configured subscription builders.
///
- private IList> Subscriptions { get; } = new List>();
+ private List> Subscriptions { get; } = [];
- private IDictionary SubscriptionGroupSettings { get; } =
- new Dictionary();
+ private Dictionary SubscriptionGroupSettings { get; } = new();
///
/// Configure the default settings for all subscription groups.
@@ -242,14 +241,8 @@ internal void Configure(
IAwsClientFactoryProxy awsClientFactoryProxy,
ILoggerFactory loggerFactory)
{
- var resolver = Parent.ServicesBuilder?.HandlerResolver?.Invoke() ??
- Parent.ServiceResolver.ResolveService();
-
- if (resolver == null)
- {
- throw new InvalidOperationException($"No {nameof(IHandlerResolver)} is registered.");
- }
-
+ var resolver = (Parent.ServicesBuilder?.HandlerResolver?.Invoke() ??
+ Parent.ServiceResolver.ResolveService()) ?? throw new InvalidOperationException($"No {nameof(IHandlerResolver)} is registered.");
Defaults.Validate();
bus.SetGroupSettings(Defaults, SubscriptionGroupSettings);
diff --git a/src/JustSaying/Fluent/TopicAddressPublisher.cs b/src/JustSaying/Fluent/TopicAddressPublisher.cs
index a9c745d7d..f7b393dbe 100644
--- a/src/JustSaying/Fluent/TopicAddressPublisher.cs
+++ b/src/JustSaying/Fluent/TopicAddressPublisher.cs
@@ -9,9 +9,12 @@ namespace JustSaying.Fluent;
///
/// An SNS message publisher for a .
///
-internal sealed class TopicAddressPublisher : SnsMessagePublisher
+internal sealed class TopicAddressPublisher(
+ IAmazonSimpleNotificationService snsClient,
+ ILoggerFactory loggerFactory,
+ IMessageSubjectProvider subjectProvider,
+ IMessageSerializationRegister serializationRegister,
+ Func handleException,
+ TopicAddress topicAddress) : SnsMessagePublisher(topicAddress.TopicArn, snsClient, serializationRegister, loggerFactory, subjectProvider, handleException)
{
- public TopicAddressPublisher(IAmazonSimpleNotificationService snsClient, ILoggerFactory loggerFactory, IMessageSubjectProvider subjectProvider, IMessageSerializationRegister serializationRegister, Func handleException, TopicAddress topicAddress)
- : base(topicAddress.TopicArn, snsClient, serializationRegister, loggerFactory, subjectProvider, handleException)
- { }
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Fluent/TopicSubscriptionBuilder`1.cs b/src/JustSaying/Fluent/TopicSubscriptionBuilder`1.cs
index c26fbff1d..977828070 100644
--- a/src/JustSaying/Fluent/TopicSubscriptionBuilder`1.cs
+++ b/src/JustSaying/Fluent/TopicSubscriptionBuilder`1.cs
@@ -211,13 +211,7 @@ void ISubscriptionBuilder.Configure(
subscriptionConfig.QueueName);
var resolutionContext = new HandlerResolutionContext(subscriptionConfig.QueueName);
- var proposedHandler = handlerResolver.ResolveHandler(resolutionContext);
- if (proposedHandler == null)
- {
- throw new HandlerNotRegisteredWithContainerException(
- $"There is no handler for '{typeof(T)}' messages.");
- }
-
+ var proposedHandler = handlerResolver.ResolveHandler(resolutionContext) ?? throw new HandlerNotRegisteredWithContainerException($"There is no handler for '{typeof(T)}' messages.");
var middlewareBuilder = new HandlerMiddlewareBuilder(handlerResolver, serviceResolver);
var handlerMiddleware = middlewareBuilder
.Configure(MiddlewareConfiguration ?? (builder => builder.UseDefaults(proposedHandler.GetType())) )
diff --git a/src/JustSaying/HandlerResolutionContext.cs b/src/JustSaying/HandlerResolutionContext.cs
index b534220ce..49d464f0a 100644
--- a/src/JustSaying/HandlerResolutionContext.cs
+++ b/src/JustSaying/HandlerResolutionContext.cs
@@ -1,11 +1,6 @@
namespace JustSaying;
-public class HandlerResolutionContext
+public class HandlerResolutionContext(string queueName)
{
- public HandlerResolutionContext(string queueName)
- {
- QueueName = queueName;
- }
-
- public string QueueName { get; private set; }
-}
\ No newline at end of file
+ public string QueueName { get; private set; } = queueName;
+}
diff --git a/src/JustSaying/IMessagingConfig.cs b/src/JustSaying/IMessagingConfig.cs
index 92fa88b7d..ea029a05f 100644
--- a/src/JustSaying/IMessagingConfig.cs
+++ b/src/JustSaying/IMessagingConfig.cs
@@ -10,4 +10,4 @@ public interface IMessagingConfig : IPublishConfiguration
ITopicNamingConvention TopicNamingConvention { get; set; }
IQueueNamingConvention QueueNamingConvention { get; set; }
void Validate();
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/IPublishConfiguration.cs b/src/JustSaying/IPublishConfiguration.cs
index c544c695c..b1206a423 100644
--- a/src/JustSaying/IPublishConfiguration.cs
+++ b/src/JustSaying/IPublishConfiguration.cs
@@ -9,4 +9,4 @@ public interface IPublishConfiguration
TimeSpan PublishFailureBackoff { get; set; }
Action MessageResponseLogger { get; set; }
IReadOnlyCollection AdditionalSubscriberAccounts { get; set; }
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/JustSayingBus.cs b/src/JustSaying/JustSayingBus.cs
index a0bd7b8cb..c5fbc347e 100644
--- a/src/JustSaying/JustSayingBus.cs
+++ b/src/JustSaying/JustSayingBus.cs
@@ -19,7 +19,7 @@ public sealed class JustSayingBus : IMessagingBus, IMessagePublisher, IDisposabl
private readonly ILogger _log;
private readonly ILoggerFactory _loggerFactory;
- private readonly SemaphoreSlim _startLock = new SemaphoreSlim(1, 1);
+ private readonly SemaphoreSlim _startLock = new(1, 1);
private bool _busStarted;
private readonly List> _startupTasks;
@@ -49,14 +49,14 @@ public JustSayingBus(
_loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
_monitor = monitor ?? throw new ArgumentNullException(nameof(monitor));
- _startupTasks = new List>();
+ _startupTasks = [];
_log = _loggerFactory.CreateLogger("JustSaying");
Config = config;
SerializationRegister = serializationRegister;
MiddlewareMap = new MiddlewareMap();
- _publishersByType = new Dictionary();
+ _publishersByType = [];
_subscriptionGroupSettings =
new ConcurrentDictionary(StringComparer.Ordinal);
_defaultSubscriptionGroupSettings = new SubscriptionGroupSettingsBuilder();
@@ -212,10 +212,8 @@ private IMessagePublisher GetPublisherForMessage(Message message)
{
if (_publishersByType.Count == 0)
{
- var errorMessage =
- "Error publishing message, no publishers registered. Has the bus been started?";
- _log.LogError(errorMessage);
- throw new InvalidOperationException(errorMessage);
+ _log.LogError("Error publishing message, no publishers registered. Has the bus been started?");
+ throw new InvalidOperationException("Error publishing message, no publishers registered. Has the bus been started?");
}
var messageType = message.GetType();
diff --git a/src/JustSaying/Messaging/Channels/Dispatch/MultiplexerSubscriber.cs b/src/JustSaying/Messaging/Channels/Dispatch/MultiplexerSubscriber.cs
index a3a8a4491..791fa6de3 100644
--- a/src/JustSaying/Messaging/Channels/Dispatch/MultiplexerSubscriber.cs
+++ b/src/JustSaying/Messaging/Channels/Dispatch/MultiplexerSubscriber.cs
@@ -4,22 +4,12 @@
namespace JustSaying.Messaging.Channels.Dispatch;
-internal class MultiplexerSubscriber : IMultiplexerSubscriber
+internal class MultiplexerSubscriber(
+ IMessageDispatcher dispatcher,
+ string subscriberId,
+ ILogger logger) : IMultiplexerSubscriber
{
private IAsyncEnumerable _messageSource;
- private readonly IMessageDispatcher _dispatcher;
- private readonly string _subscriberId;
- private readonly ILogger _logger;
-
- public MultiplexerSubscriber(
- IMessageDispatcher dispatcher,
- string subscriberId,
- ILogger logger)
- {
- _dispatcher = dispatcher;
- _subscriberId = subscriberId;
- _logger = logger;
- }
public void Subscribe(IAsyncEnumerable messageSource)
{
@@ -30,17 +20,17 @@ public async Task RunAsync(CancellationToken stoppingToken)
{
await Task.Yield();
- _logger.LogTrace("Starting up {StartupType} with Id {SubscriberId}",
+ logger.LogTrace("Starting up {StartupType} with Id {SubscriberId}",
nameof(MultiplexerSubscriber),
- _subscriberId);
+ subscriberId);
await foreach (IQueueMessageContext messageContext in _messageSource.WithCancellation(
stoppingToken))
{
stoppingToken.ThrowIfCancellationRequested();
- await _dispatcher.DispatchMessageAsync(messageContext, stoppingToken)
+ await dispatcher.DispatchMessageAsync(messageContext, stoppingToken)
.ConfigureAwait(false);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Messaging/Channels/Multiplexer/MergingMultiplexer.cs b/src/JustSaying/Messaging/Channels/Multiplexer/MergingMultiplexer.cs
index a98a1365c..1dc192243 100644
--- a/src/JustSaying/Messaging/Channels/Multiplexer/MergingMultiplexer.cs
+++ b/src/JustSaying/Messaging/Channels/Multiplexer/MergingMultiplexer.cs
@@ -14,18 +14,18 @@ internal sealed class MergingMultiplexer : IMultiplexer, IDisposable
private CancellationToken _stoppingToken;
private Task _completion;
- private readonly IList> _readers;
+ private readonly List> _readers;
private readonly Channel _targetChannel;
private readonly int _channelCapacity;
- private readonly SemaphoreSlim _readersLock = new SemaphoreSlim(1, 1);
- private readonly object _startLock = new object();
+ private readonly SemaphoreSlim _readersLock = new(1, 1);
+ private readonly object _startLock = new();
public MergingMultiplexer(
int channelCapacity,
ILogger logger)
{
- _readers = new List>();
+ _readers = [];
_logger = logger;
_channelCapacity = channelCapacity;
@@ -125,4 +125,4 @@ public void Dispose()
_completion = null;
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Messaging/Channels/Receive/MessageReceiveBuffer.cs b/src/JustSaying/Messaging/Channels/Receive/MessageReceiveBuffer.cs
index b9fc79d07..5d53c24ea 100644
--- a/src/JustSaying/Messaging/Channels/Receive/MessageReceiveBuffer.cs
+++ b/src/JustSaying/Messaging/Channels/Receive/MessageReceiveBuffer.cs
@@ -26,7 +26,7 @@ internal class MessageReceiveBuffer : IMessageReceiveBuffer
private readonly IMessageMonitor _monitor;
private readonly ILogger _logger;
- private readonly HashSet _requestMessageAttributeNames = new HashSet();
+ private readonly HashSet _requestMessageAttributeNames = new();
public ChannelReader Reader => _channel.Reader;
diff --git a/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroup.cs b/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroup.cs
index ae8ede65a..d7a3d0835 100644
--- a/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroup.cs
+++ b/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroup.cs
@@ -7,54 +7,40 @@
namespace JustSaying.Messaging.Channels.SubscriptionGroups;
///
-internal class SubscriptionGroup : ISubscriptionGroup
+///
+/// Coordinates reading messages from a collection of
+/// and dispatching using a collection of .
+///
+/// The to use.
+/// The collection of to read from.
+/// The to aggregate all messages into one stream.
+/// The collection of that will dispatch the messages
+/// The to be used.
+internal class SubscriptionGroup(
+ SubscriptionGroupSettings settings,
+ ICollection receiveBuffers,
+ IMultiplexer multiplexer,
+ ICollection subscribers,
+ ILogger logger) : ISubscriptionGroup
{
- private readonly ICollection _receiveBuffers;
- private readonly SubscriptionGroupSettings _settings;
- private readonly IMultiplexer _multiplexer;
- private readonly ICollection _subscribers;
- private readonly ILogger _logger;
-
- ///
- /// Coordinates reading messages from a collection of
- /// and dispatching using a collection of .
- ///
- /// The to use.
- /// The collection of to read from.
- /// The to aggregate all messages into one stream.
- /// The collection of that will dispatch the messages
- /// The to be used.
- public SubscriptionGroup(
- SubscriptionGroupSettings settings,
- ICollection receiveBuffers,
- IMultiplexer multiplexer,
- ICollection subscribers,
- ILogger logger)
- {
- _receiveBuffers = receiveBuffers;
- _settings = settings;
- _multiplexer = multiplexer;
- _subscribers = subscribers;
- _logger = logger;
- }
-
///
public Task RunAsync(CancellationToken stoppingToken)
{
- var receiveBufferQueueNames = string.Join(",", _receiveBuffers.Select(rb => rb.QueueName));
+ var receiveBufferQueueNames = string.Join(",", receiveBuffers.Select(rb => rb.QueueName));
- _logger.LogInformation(
- "Starting up SubscriptionGroup {SubscriptionGroupName} for queues [{Queues}] with {ReceiveBuffferCount} receive buffers and {SubscriberCount} subscribers.",
- _settings.Name,
+ logger.LogInformation(
+ "Starting up SubscriptionGroup {SubscriptionGroupName} for queues [{Queues}] with {ReceiveBufferCount} receive buffers and {SubscriberCount} subscribers.",
+ settings.Name,
receiveBufferQueueNames,
- _receiveBuffers.Count,
- _subscribers.Count);
-
- var completionTasks = new List();
+ receiveBuffers.Count,
+ subscribers.Count);
- completionTasks.Add(_multiplexer.RunAsync(stoppingToken));
- completionTasks.AddRange(_subscribers.Select(subscriber => subscriber.RunAsync(stoppingToken)));
- completionTasks.AddRange(_receiveBuffers.Select(buffer => buffer.RunAsync(stoppingToken)));
+ var completionTasks = new List
+ {
+ multiplexer.RunAsync(stoppingToken)
+ };
+ completionTasks.AddRange(subscribers.Select(subscriber => subscriber.RunAsync(stoppingToken)));
+ completionTasks.AddRange(receiveBuffers.Select(buffer => buffer.RunAsync(stoppingToken)));
return Task.WhenAll(completionTasks);
}
@@ -64,10 +50,10 @@ public InterrogationResult Interrogate()
{
return new InterrogationResult(new
{
- _settings.Name,
- ConcurrencyLimit = _subscribers.Count,
- Multiplexer = _multiplexer.Interrogate(),
- ReceiveBuffers = _receiveBuffers.Select(rb => rb.Interrogate()).ToArray(),
+ settings.Name,
+ ConcurrencyLimit = subscribers.Count,
+ Multiplexer = multiplexer.Interrogate(),
+ ReceiveBuffers = receiveBuffers.Select(rb => rb.Interrogate()).ToArray(),
});
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupCollection.cs b/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupCollection.cs
index 092919c0e..84627afb4 100644
--- a/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupCollection.cs
+++ b/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupCollection.cs
@@ -4,27 +4,20 @@
namespace JustSaying.Messaging.Channels.SubscriptionGroups;
///
-public class SubscriptionGroupCollection : ISubscriptionGroup
+///
+/// Runs multiple instances of .
+///
+/// The collection of instances to run.
+/// The to use.
+public class SubscriptionGroupCollection(
+ IList subscriptionGroups,
+ ILogger logger) : ISubscriptionGroup
{
- private readonly ILogger _logger;
- private readonly IList _subscriptionGroups;
-
- ///
- /// Runs multiple instances of .
- ///
- /// The collection of instances to run.
- /// The to use.
- public SubscriptionGroupCollection(
- IList subscriptionGroups,
- ILogger logger)
- {
- _subscriptionGroups = subscriptionGroups ?? throw new System.ArgumentNullException(nameof(subscriptionGroups));
- _logger = logger ?? throw new System.ArgumentNullException(nameof(logger));
- }
-
+ private readonly ILogger _logger = logger ?? throw new ArgumentNullException(nameof(logger));
+ private readonly IList _subscriptionGroups = subscriptionGroups ?? throw new ArgumentNullException(nameof(subscriptionGroups));
private Task _completion;
private bool _started;
- private readonly object _startLock = new object();
+ private readonly object _startLock = new();
///
public Task RunAsync(CancellationToken stoppingToken)
@@ -66,4 +59,4 @@ private Task RunImplAsync(CancellationToken stoppingToken)
return Task.WhenAll(completionTasks);
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupConfigBuilder.cs b/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupConfigBuilder.cs
index a55bfd748..0107620c4 100644
--- a/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupConfigBuilder.cs
+++ b/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupConfigBuilder.cs
@@ -9,9 +9,14 @@ namespace JustSaying.Messaging.Channels.SubscriptionGroups;
/// are combined with overrides set here to create a final configuration
/// that can be inspected via .
///
-public class SubscriptionGroupConfigBuilder
+///
+/// Creates an instance of .
+///
+/// The name of the subscription group.
+public class SubscriptionGroupConfigBuilder(string groupName)
{
- private readonly List _sqsQueues;
+ private readonly List _sqsQueues = [];
+ private readonly string _groupName = groupName ?? throw new ArgumentNullException(nameof(groupName));
private int? _bufferSize;
private TimeSpan? _receiveBufferReadTimeout;
@@ -20,18 +25,6 @@ public class SubscriptionGroupConfigBuilder
private int? _multiplexerCapacity;
private int? _prefetch;
- private readonly string _groupName;
-
- ///
- /// Creates an instance of .
- ///
- /// The name of the subscription group.
- public SubscriptionGroupConfigBuilder(string groupName)
- {
- _groupName = groupName ?? throw new ArgumentNullException(nameof(groupName));
- _sqsQueues = new List();
- }
-
///
/// Adds an to be consumed by this .
///
diff --git a/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupFactory.cs b/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupFactory.cs
index 63b144a13..bb3dcc5c3 100644
--- a/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupFactory.cs
+++ b/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupFactory.cs
@@ -69,7 +69,7 @@ public ISubscriptionGroup Create(
{
ReceiveMiddleware receiveMiddleware = defaults.SqsMiddleware ?? _defaultSqsMiddleware;
- List groups = subscriptionGroupSettings
+ var groups = subscriptionGroupSettings
.Values
.Select(builder => Create(receiveMiddleware, builder.Build(defaults)))
.ToList();
@@ -81,7 +81,7 @@ public ISubscriptionGroup Create(
private ISubscriptionGroup Create(ReceiveMiddleware receiveMiddleware, SubscriptionGroupSettings settings)
{
- IMultiplexer multiplexer = CreateMultiplexer(settings.MultiplexerCapacity);
+ var multiplexer = CreateMultiplexer(settings.MultiplexerCapacity);
ICollection receiveBuffers = CreateBuffers(receiveMiddleware, settings);
ICollection subscribers = CreateSubscribers(settings);
@@ -103,11 +103,11 @@ private ISubscriptionGroup Create(ReceiveMiddleware receiveMiddleware, Subscript
_loggerFactory.CreateLogger());
}
- private ICollection CreateBuffers(
+ private List CreateBuffers(
ReceiveMiddleware receiveMiddleware,
SubscriptionGroupSettings subscriptionGroupSettings)
{
- var buffers = new List();
+ List buffers = [];
var logger = _loggerFactory.CreateLogger();
@@ -130,14 +130,14 @@ private ICollection CreateBuffers(
return buffers;
}
- private IMultiplexer CreateMultiplexer(int channelCapacity)
+ private MergingMultiplexer CreateMultiplexer(int channelCapacity)
{
return new MergingMultiplexer(
channelCapacity,
_loggerFactory.CreateLogger());
}
- private ICollection CreateSubscribers(SubscriptionGroupSettings settings)
+ private List CreateSubscribers(SubscriptionGroupSettings settings)
{
var logger = _loggerFactory.CreateLogger();
diff --git a/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupSettings.cs b/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupSettings.cs
index cce25349f..7e7bfc5cc 100644
--- a/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupSettings.cs
+++ b/src/JustSaying/Messaging/Channels/SubscriptionGroups/SubscriptionGroupSettings.cs
@@ -55,7 +55,7 @@ internal SubscriptionGroupSettings(
public int MultiplexerCapacity { get; }
///
- /// Gets the maxiumum number of messages to fetch from SQS in each request.
+ /// Gets the maximum number of messages to fetch from SQS in each request.
///
public int Prefetch { get; }
diff --git a/src/JustSaying/Messaging/Interrogation/InterrogationResult.cs b/src/JustSaying/Messaging/Interrogation/InterrogationResult.cs
index 498b939ff..1423679d9 100644
--- a/src/JustSaying/Messaging/Interrogation/InterrogationResult.cs
+++ b/src/JustSaying/Messaging/Interrogation/InterrogationResult.cs
@@ -6,20 +6,15 @@ namespace JustSaying.Messaging.Interrogation;
/// This type represents the result of interrogating a bus component.
///
[JsonConverter(typeof(InterrogationResultJsonConverter))]
-public sealed class InterrogationResult
+public sealed class InterrogationResult(object data)
{
- public InterrogationResult(object data)
- {
- Data = data;
- }
-
///
/// Serialize this to JSON and log it on startup to gain some valuable insights into what's
/// going on inside JustSaying.
///
/// This property is intentionally untyped, because it is unstructured and subject to change.
/// It should only be used for diagnostic purposes.
- public object Data { get; }
+ public object Data { get; } = data;
internal static InterrogationResult Empty { get; } = new InterrogationResult(new {});
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Messaging/MessageHandling/ListHandler.cs b/src/JustSaying/Messaging/MessageHandling/ListHandler.cs
index b153aada7..147e7f714 100644
--- a/src/JustSaying/Messaging/MessageHandling/ListHandler.cs
+++ b/src/JustSaying/Messaging/MessageHandling/ListHandler.cs
@@ -1,20 +1,13 @@
namespace JustSaying.Messaging.MessageHandling;
-public class ListHandler : IHandlerAsync
+public class ListHandler(IEnumerable> handlers) : IHandlerAsync
{
- private readonly IEnumerable> _handlers;
-
- public ListHandler(IEnumerable> handlers)
- {
- _handlers = handlers;
- }
-
public async Task Handle(T message)
{
- var handlerTasks = _handlers.Select(h => h.Handle(message));
+ var handlerTasks = handlers.Select(h => h.Handle(message));
var handlerResults = await Task.WhenAll(handlerTasks)
.ConfigureAwait(false);
return handlerResults.All(x => x);
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Messaging/MessageHandling/MessageAttributes.cs b/src/JustSaying/Messaging/MessageHandling/MessageAttributes.cs
index 43bc0951f..aea001e35 100644
--- a/src/JustSaying/Messaging/MessageHandling/MessageAttributes.cs
+++ b/src/JustSaying/Messaging/MessageHandling/MessageAttributes.cs
@@ -5,14 +5,9 @@ namespace JustSaying.Messaging.MessageHandling;
///
/// A collection of values returned by .
///
-public class MessageAttributes
+public class MessageAttributes(Dictionary attributes)
{
- private readonly IDictionary _attributes;
-
- public MessageAttributes(Dictionary attributes)
- {
- _attributes = attributes ?? throw new ArgumentNullException(nameof(attributes));
- }
+ private readonly Dictionary _attributes = attributes ?? throw new ArgumentNullException(nameof(attributes));
public MessageAttributes()
: this(new Dictionary())
@@ -21,4 +16,4 @@ public MessageAttributes()
public MessageAttributeValue Get(string value)
=> _attributes.TryGetValue(value, out MessageAttributeValue result) ? result : null;
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Messaging/MessageHandling/MessageContext.cs b/src/JustSaying/Messaging/MessageHandling/MessageContext.cs
index 77d45456c..d200d17a5 100644
--- a/src/JustSaying/Messaging/MessageHandling/MessageContext.cs
+++ b/src/JustSaying/Messaging/MessageHandling/MessageContext.cs
@@ -5,33 +5,27 @@ namespace JustSaying.Messaging.MessageHandling;
///
/// Context metadata about the SQS message currently being processed.
///
-public class MessageContext
+///
+/// Creates an instance of .
+///
+/// The currently being processed.
+/// The URI of the SQS queue the message is from.
+/// The from the message.
+public class MessageContext(SQSMessage message, Uri queueUri, MessageAttributes messageAttributes)
{
- ///
- /// Creates an instance of .
- ///
- /// The currently being processed.
- /// The URI of the SQS queue the message is from.
- /// The from the message.
- public MessageContext(SQSMessage message, Uri queueUri, MessageAttributes messageAttributes)
- {
- Message = message ?? throw new ArgumentNullException(nameof(message));
- QueueUri = queueUri ?? throw new ArgumentNullException(nameof(queueUri));
- MessageAttributes = messageAttributes ?? throw new ArgumentNullException(nameof(messageAttributes));
- }
///
/// Gets the AWS SQS Message that is currently being processed.
///
- public SQSMessage Message { get; }
+ public SQSMessage Message { get; } = message ?? throw new ArgumentNullException(nameof(message));
///
/// Gets the SQS Queue that the message was received on.
///
- public Uri QueueUri { get; }
+ public Uri QueueUri { get; } = queueUri ?? throw new ArgumentNullException(nameof(queueUri));
///
/// Gets a collection of 's that were sent with this message.
///
- public MessageAttributes MessageAttributes { get; }
+ public MessageAttributes MessageAttributes { get; } = messageAttributes ?? throw new ArgumentNullException(nameof(messageAttributes));
}
\ No newline at end of file
diff --git a/src/JustSaying/Messaging/MessageHandling/MessageContextAccessor.cs b/src/JustSaying/Messaging/MessageHandling/MessageContextAccessor.cs
index 3d609911e..b054f385c 100644
--- a/src/JustSaying/Messaging/MessageHandling/MessageContextAccessor.cs
+++ b/src/JustSaying/Messaging/MessageHandling/MessageContextAccessor.cs
@@ -2,11 +2,11 @@ namespace JustSaying.Messaging.MessageHandling;
public class MessageContextAccessor : IMessageContextReader, IMessageContextAccessor
{
- private static readonly AsyncLocal Context = new AsyncLocal();
+ private static readonly AsyncLocal Context = new();
public MessageContext MessageContext
{
get => Context.Value;
set => Context.Value = value;
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Messaging/MessageSerialization/GenericMessageSubjectProvider.cs b/src/JustSaying/Messaging/MessageSerialization/GenericMessageSubjectProvider.cs
index fa8c290a3..0be4d9174 100644
--- a/src/JustSaying/Messaging/MessageSerialization/GenericMessageSubjectProvider.cs
+++ b/src/JustSaying/Messaging/MessageSerialization/GenericMessageSubjectProvider.cs
@@ -25,4 +25,4 @@ public string GetSubjectForType(Type messageType) =>
.Join("_",
Flatten(messageType).Select(t => Regex.Replace(t.Name + "_" + t.Namespace, "\\W", "_")))
.TruncateTo(MAX_SNS_SUBJECT_LENGTH);
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Messaging/MessageSerialization/MessageSerializationRegister.cs b/src/JustSaying/Messaging/MessageSerialization/MessageSerializationRegister.cs
index 5c56b24ab..3fa3fb4b9 100644
--- a/src/JustSaying/Messaging/MessageSerialization/MessageSerializationRegister.cs
+++ b/src/JustSaying/Messaging/MessageSerialization/MessageSerializationRegister.cs
@@ -3,19 +3,15 @@
namespace JustSaying.Messaging.MessageSerialization;
-public class MessageSerializationRegister : IMessageSerializationRegister
+public class MessageSerializationRegister(
+ IMessageSubjectProvider messageSubjectProvider,
+ IMessageSerializationFactory serializationFactory) : IMessageSerializationRegister
{
- private readonly IMessageSubjectProvider _messageSubjectProvider;
- private readonly IMessageSerializationFactory _serializationFactory;
+ private readonly IMessageSubjectProvider _messageSubjectProvider = messageSubjectProvider ?? throw new ArgumentNullException(nameof(messageSubjectProvider));
+ private readonly IMessageSerializationFactory _serializationFactory = serializationFactory;
private readonly ConcurrentDictionary> _typeSerializersBySubject = new(StringComparer.OrdinalIgnoreCase);
private readonly HashSet _messageSerializers = new();
- public MessageSerializationRegister(IMessageSubjectProvider messageSubjectProvider, IMessageSerializationFactory serializationFactory)
- {
- _messageSubjectProvider = messageSubjectProvider ?? throw new ArgumentNullException(nameof(messageSubjectProvider));
- _serializationFactory = serializationFactory;
- }
-
public void AddSerializer() where T : Message
{
string key = _messageSubjectProvider.GetSubjectForType(typeof(T));
diff --git a/src/JustSaying/Messaging/MessageSerialization/MessageWithAttributes.cs b/src/JustSaying/Messaging/MessageSerialization/MessageWithAttributes.cs
index d4abfdedd..d57fdaac1 100644
--- a/src/JustSaying/Messaging/MessageSerialization/MessageWithAttributes.cs
+++ b/src/JustSaying/Messaging/MessageSerialization/MessageWithAttributes.cs
@@ -6,21 +6,15 @@ namespace JustSaying.Messaging.MessageSerialization;
///
/// Represents a deserialized message with attributes.
///
-public class MessageWithAttributes
+public class MessageWithAttributes(Message message, MessageAttributes messageAttributes)
{
- public MessageWithAttributes(Message message, MessageAttributes messageAttributes)
- {
- Message = message;
- MessageAttributes = messageAttributes;
- }
-
///
/// Gets the message that was extracted from a message body.
///
- public Message Message { get; }
+ public Message Message { get; } = message;
///
/// Gets the attributes that were extracted from a message body.
///
- public MessageAttributes MessageAttributes { get; }
-}
\ No newline at end of file
+ public MessageAttributes MessageAttributes { get; } = messageAttributes;
+}
diff --git a/src/JustSaying/Messaging/MessageSerialization/NewtonsoftSerializationFactory.cs b/src/JustSaying/Messaging/MessageSerialization/NewtonsoftSerializationFactory.cs
index cef08b5ec..da7ebbe97 100644
--- a/src/JustSaying/Messaging/MessageSerialization/NewtonsoftSerializationFactory.cs
+++ b/src/JustSaying/Messaging/MessageSerialization/NewtonsoftSerializationFactory.cs
@@ -3,19 +3,14 @@
namespace JustSaying.Messaging.MessageSerialization;
-public class NewtonsoftSerializationFactory : IMessageSerializationFactory
+public class NewtonsoftSerializationFactory(JsonSerializerSettings settings) : IMessageSerializationFactory
{
- private readonly NewtonsoftSerializer _serializer;
+ private readonly NewtonsoftSerializer _serializer = new(settings);
public NewtonsoftSerializationFactory()
: this(null)
{
}
- public NewtonsoftSerializationFactory(JsonSerializerSettings settings)
- {
- _serializer = new NewtonsoftSerializer(settings);
- }
-
public IMessageSerializer GetSerializer() where T : Message => _serializer;
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Messaging/MessageSerialization/NewtonsoftSerializer.cs b/src/JustSaying/Messaging/MessageSerialization/NewtonsoftSerializer.cs
index 6a546423f..68c5b5d25 100644
--- a/src/JustSaying/Messaging/MessageSerialization/NewtonsoftSerializer.cs
+++ b/src/JustSaying/Messaging/MessageSerialization/NewtonsoftSerializer.cs
@@ -16,14 +16,11 @@ public NewtonsoftSerializer()
public NewtonsoftSerializer(JsonSerializerSettings settings)
{
- if (settings == null)
- {
- settings = new JsonSerializerSettings
+ settings ??= new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
Converters = new JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter() }
};
- }
_settings = settings;
}
@@ -91,4 +88,4 @@ public string GetMessageSubject(string sqsMessage)
var body = JObject.Parse(sqsMessage);
return body.Value("Subject") ?? string.Empty;
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Messaging/MessageSerialization/SystemTextJsonSerializationFactory.cs b/src/JustSaying/Messaging/MessageSerialization/SystemTextJsonSerializationFactory.cs
index 7bb59b9fb..023957b78 100644
--- a/src/JustSaying/Messaging/MessageSerialization/SystemTextJsonSerializationFactory.cs
+++ b/src/JustSaying/Messaging/MessageSerialization/SystemTextJsonSerializationFactory.cs
@@ -3,19 +3,14 @@
namespace JustSaying.Messaging.MessageSerialization;
-public class SystemTextJsonSerializationFactory : IMessageSerializationFactory
+public class SystemTextJsonSerializationFactory(JsonSerializerOptions options) : IMessageSerializationFactory
{
- private readonly SystemTextJsonSerializer _serializer;
+ private readonly SystemTextJsonSerializer _serializer = new(options);
public SystemTextJsonSerializationFactory()
: this(null)
{
}
- public SystemTextJsonSerializationFactory(JsonSerializerOptions options)
- {
- _serializer = new SystemTextJsonSerializer(options);
- }
-
public IMessageSerializer GetSerializer() where T : Message => _serializer;
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Messaging/MessageSerialization/SystemTextJsonSerializer.cs b/src/JustSaying/Messaging/MessageSerialization/SystemTextJsonSerializer.cs
index 7a4cbd68f..50f5c2697 100644
--- a/src/JustSaying/Messaging/MessageSerialization/SystemTextJsonSerializer.cs
+++ b/src/JustSaying/Messaging/MessageSerialization/SystemTextJsonSerializer.cs
@@ -42,17 +42,15 @@ public SystemTextJsonSerializer(JsonSerializerOptions options)
///
public string GetMessageSubject(string sqsMessage)
{
- using (var body = JsonDocument.Parse(sqsMessage))
- {
- string subject = string.Empty;
-
- if (body.RootElement.TryGetProperty("Subject", out var value))
- {
- subject = value.GetString() ?? string.Empty;
- }
+ using var body = JsonDocument.Parse(sqsMessage);
+ string subject = string.Empty;
- return subject;
+ if (body.RootElement.TryGetProperty("Subject", out var value))
+ {
+ subject = value.GetString() ?? string.Empty;
}
+
+ return subject;
}
public MessageAttributes GetMessageAttributes(string message)
@@ -86,13 +84,11 @@ public MessageAttributes GetMessageAttributes(string message)
///
public Message Deserialize(string message, Type type)
{
- using (var document = JsonDocument.Parse(message))
- {
- JsonElement element = document.RootElement.GetProperty("Message");
- string json = element.ToString();
+ using var document = JsonDocument.Parse(message);
+ JsonElement element = document.RootElement.GetProperty("Message");
+ string json = element.ToString();
- return (Message)JsonSerializer.Deserialize(json, type, _options);
- }
+ return (Message)JsonSerializer.Deserialize(json, type, _options);
}
///
diff --git a/src/JustSaying/Messaging/MessageSerialization/TypeSerializer.cs b/src/JustSaying/Messaging/MessageSerialization/TypeSerializer.cs
index f58986ba2..6f116d7b9 100644
--- a/src/JustSaying/Messaging/MessageSerialization/TypeSerializer.cs
+++ b/src/JustSaying/Messaging/MessageSerialization/TypeSerializer.cs
@@ -1,13 +1,7 @@
namespace JustSaying.Messaging.MessageSerialization;
-public class TypeSerializer
+public class TypeSerializer(Type type, IMessageSerializer serializer)
{
- public Type Type { get; private set; }
- public IMessageSerializer Serializer { get; private set; }
-
- public TypeSerializer(Type type, IMessageSerializer serializer)
- {
- Type = type;
- Serializer = serializer;
- }
-}
\ No newline at end of file
+ public Type Type { get; private set; } = type;
+ public IMessageSerializer Serializer { get; private set; } = serializer;
+}
diff --git a/src/JustSaying/Messaging/Middleware/Backoff/BackoffMiddleware.cs b/src/JustSaying/Messaging/Middleware/Backoff/BackoffMiddleware.cs
index b2d05640c..15a75c35a 100644
--- a/src/JustSaying/Messaging/Middleware/Backoff/BackoffMiddleware.cs
+++ b/src/JustSaying/Messaging/Middleware/Backoff/BackoffMiddleware.cs
@@ -10,25 +10,18 @@ namespace JustSaying.Messaging.Middleware.Backoff;
///
/// Implements a middleware that will execute an to delay message redelivery when a handler returns false or throws.
///
-public sealed class BackoffMiddleware : MiddlewareBase
+///
+/// Constructs a with a given backoff strategy and logger/monitor.
+///
+/// An to use to determine how long to delay message redelivery when a handler returns false or throws.
+/// An to use when logging request failures.
+/// An to use when recording request failures.
+public sealed class BackoffMiddleware(IMessageBackoffStrategy backoffStrategy, ILoggerFactory loggerFactory, IMessageMonitor monitor) : MiddlewareBase
{
- private readonly IMessageBackoffStrategy _backoffStrategy;
- private readonly ILogger _logger;
- private readonly IMessageMonitor _monitor;
-
- ///
- /// Constructs a with a given backoff strategy and logger/monitor.
- ///
- /// An to use to determine how long to delay message redelivery when a handler returns false or throws.
- /// An to use when logging request failures.
- /// An to use when recording request failures.
- public BackoffMiddleware(IMessageBackoffStrategy backoffStrategy, ILoggerFactory loggerFactory, IMessageMonitor monitor)
- {
- _backoffStrategy = backoffStrategy ?? throw new ArgumentNullException(nameof(backoffStrategy));
- _monitor = monitor ?? throw new ArgumentNullException(nameof(monitor));
- _logger = loggerFactory?.CreateLogger() ??
+ private readonly IMessageBackoffStrategy _backoffStrategy = backoffStrategy ?? throw new ArgumentNullException(nameof(backoffStrategy));
+ private readonly ILogger _logger = loggerFactory?.CreateLogger() ??
throw new ArgumentNullException(nameof(loggerFactory));
- }
+ private readonly IMessageMonitor _monitor = monitor ?? throw new ArgumentNullException(nameof(monitor));
protected override async Task RunInnerAsync(HandleMessageContext context, Func> func, CancellationToken stoppingToken)
{
@@ -70,7 +63,7 @@ private async Task TryUpdateVisibilityTimeout(HandleMessageContext context, Canc
}
private static bool TryGetApproxReceiveCount(
- IDictionary attributes,
+ Dictionary attributes,
out int approxReceiveCount)
{
approxReceiveCount = 0;
@@ -82,4 +75,4 @@ private static bool TryGetApproxReceiveCount(
CultureInfo.InvariantCulture,
out approxReceiveCount);
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Messaging/Middleware/DelegateMiddleware`2.cs b/src/JustSaying/Messaging/Middleware/DelegateMiddleware`2.cs
index 390f2fe8e..1d2d2a4c0 100644
--- a/src/JustSaying/Messaging/Middleware/DelegateMiddleware`2.cs
+++ b/src/JustSaying/Messaging/Middleware/DelegateMiddleware`2.cs
@@ -3,7 +3,5 @@ namespace JustSaying.Messaging.Middleware;
internal class DelegateMiddleware : MiddlewareBase
{
protected override async Task RunInnerAsync(TContext context, Func> func, CancellationToken stoppingToken)
- {
- return await func(stoppingToken).ConfigureAwait(false);
- }
-}
\ No newline at end of file
+ => await func(stoppingToken).ConfigureAwait(false);
+}
diff --git a/src/JustSaying/Messaging/Middleware/ErrorHandling/ErrorHandlerMiddleware.cs b/src/JustSaying/Messaging/Middleware/ErrorHandling/ErrorHandlerMiddleware.cs
index f3d561c03..1970a07c1 100644
--- a/src/JustSaying/Messaging/Middleware/ErrorHandling/ErrorHandlerMiddleware.cs
+++ b/src/JustSaying/Messaging/Middleware/ErrorHandling/ErrorHandlerMiddleware.cs
@@ -7,19 +7,14 @@ namespace JustSaying.Messaging.Middleware.ErrorHandling;
/// This middleware calls HandleException(Type messageType), HandleError(Exception ex, Amazon.SQS.Model.Message message),
/// and Handled(JustSaying.Models.Message message).
///
-public sealed class ErrorHandlerMiddleware : MiddlewareBase
+///
+/// Constructs an .
+///
+/// The to use to record errors.
+/// When the is null.
+public sealed class ErrorHandlerMiddleware(IMessageMonitor monitor) : MiddlewareBase
{
- private readonly IMessageMonitor _monitor;
-
- ///
- /// Constructs an .
- ///
- /// The to use to record errors.
- /// When the is null.
- public ErrorHandlerMiddleware(IMessageMonitor monitor)
- {
- _monitor = monitor ?? throw new ArgumentNullException(nameof(monitor));
- }
+ private readonly IMessageMonitor _monitor = monitor ?? throw new ArgumentNullException(nameof(monitor));
protected override async Task RunInnerAsync(HandleMessageContext context, Func> func, CancellationToken stoppingToken)
{
@@ -40,4 +35,4 @@ protected override async Task RunInnerAsync(HandleMessageContext context,
_monitor.Handled(context.Message);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Messaging/Middleware/ExactlyOnce/ExactlyOnceMiddleware.cs b/src/JustSaying/Messaging/Middleware/ExactlyOnce/ExactlyOnceMiddleware.cs
index 7afe333bc..62e06d0ea 100644
--- a/src/JustSaying/Messaging/Middleware/ExactlyOnce/ExactlyOnceMiddleware.cs
+++ b/src/JustSaying/Messaging/Middleware/ExactlyOnce/ExactlyOnceMiddleware.cs
@@ -4,24 +4,9 @@
// ReSharper disable once CheckNamespace
namespace JustSaying.Messaging.Middleware;
-public sealed class ExactlyOnceMiddleware : MiddlewareBase
+public sealed class ExactlyOnceMiddleware(IMessageLockAsync messageLock, TimeSpan timeout, string handlerName, ILogger logger) : MiddlewareBase
{
- private readonly IMessageLockAsync _messageLock;
- private readonly TimeSpan _timeout;
- private readonly string _lockSuffixKeyForHandler;
- private readonly ILogger _logger;
-
- private const bool RemoveTheMessageFromTheQueue = true;
- private const bool LeaveItInTheQueue = false;
-
- public ExactlyOnceMiddleware(IMessageLockAsync messageLock, TimeSpan timeout, string handlerName, ILogger logger)
- {
- _messageLock = messageLock;
- _timeout = timeout;
- _logger = logger;
-
- _lockSuffixKeyForHandler = $"{typeof(T).FullName.ToLowerInvariant()}-{handlerName}";
- }
+ private readonly string _lockSuffixKeyForHandler = $"{typeof(T).FullName.ToLowerInvariant()}-{handlerName}";
protected override async Task RunInnerAsync(HandleMessageContext context, Func> func, CancellationToken stoppingToken)
{
@@ -30,40 +15,40 @@ protected override async Task RunInnerAsync(HandleMessageContext context,
string lockKey = $"{context.Message.UniqueKey()}-{_lockSuffixKeyForHandler}";
- MessageLockResponse lockResponse = await _messageLock.TryAcquireLockAsync(lockKey, _timeout).ConfigureAwait(false);
+ MessageLockResponse lockResponse = await messageLock.TryAcquireLockAsync(lockKey, timeout).ConfigureAwait(false);
if (!lockResponse.DoIHaveExclusiveLock)
{
if (lockResponse.IsMessagePermanentlyLocked)
{
- _logger.LogDebug("Failed to acquire lock for message with key {MessageLockKey} as it is permanently locked.", lockKey);
- return RemoveTheMessageFromTheQueue;
+ logger.LogDebug("Failed to acquire lock for message with key {MessageLockKey} as it is permanently locked.", lockKey);
+ return true;
}
- _logger.LogDebug("Failed to acquire lock for message with key {MessageLockKey}; returning message to queue.", lockKey);
- return LeaveItInTheQueue;
+ logger.LogDebug("Failed to acquire lock for message with key {MessageLockKey}; returning message to queue.", lockKey);
+ return false;
}
try
{
- _logger.LogDebug("Acquired lock for message with key {MessageLockKey}.", lockKey);
+ logger.LogDebug("Acquired lock for message with key {MessageLockKey}.", lockKey);
bool successfullyHandled = await func(stoppingToken).ConfigureAwait(false);
if (successfullyHandled)
{
- await _messageLock.TryAcquireLockPermanentlyAsync(lockKey).ConfigureAwait(false);
+ await messageLock.TryAcquireLockPermanentlyAsync(lockKey).ConfigureAwait(false);
- _logger.LogDebug("Acquired permanent lock for message with key {MessageLockKey}.", lockKey);
+ logger.LogDebug("Acquired permanent lock for message with key {MessageLockKey}.", lockKey);
}
return successfullyHandled;
}
catch (Exception)
{
- await _messageLock.ReleaseLockAsync(lockKey).ConfigureAwait(false);
- _logger.LogDebug("Released lock for message with key {MessageLockKey}.", lockKey);
+ await messageLock.ReleaseLockAsync(lockKey).ConfigureAwait(false);
+ logger.LogDebug("Released lock for message with key {MessageLockKey}.", lockKey);
throw;
}
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Messaging/Middleware/Handle/HandleMessageContext.cs b/src/JustSaying/Messaging/Middleware/Handle/HandleMessageContext.cs
index d314dc82c..e1e8c0fca 100644
--- a/src/JustSaying/Messaging/Middleware/Handle/HandleMessageContext.cs
+++ b/src/JustSaying/Messaging/Middleware/Handle/HandleMessageContext.cs
@@ -6,69 +6,64 @@
// ReSharper disable once CheckNamespace
namespace JustSaying.Messaging.Middleware;
-public sealed class HandleMessageContext
+///
+/// This class encapsulates a messages context as it passes through a middleware pipeline.
+///
+/// The JustSaying message that was deserialized from SQS.
+/// The type of the JustSaying message contained in .
+/// The queue from which this message was received.
+/// The to use to update message visibilities on failure.
+/// The to use to remove a message from the queue on success.
+public sealed class HandleMessageContext(
+ string queueName,
+ Amazon.SQS.Model.Message rawMessage,
+ Message message,
+ Type messageType,
+ IMessageVisibilityUpdater visibilityUpdater,
+ IMessageDeleter messageDeleter,
+ Uri queueUri,
+ MessageAttributes messageAttributes)
{
- ///
- /// This class encapsulates a messages context as it passes through a middleware pipeline.
- ///
- /// The JustSaying message that was deserialized from SQS.
- /// The type of the JustSaying message contained in .
- /// The queue from which this message was received.
- /// The to use to update message visibilities on failure.
- /// The to use to remove a message from the queue on success.
- public HandleMessageContext(string queueName, Amazon.SQS.Model.Message rawMessage, Message message,
- Type messageType, IMessageVisibilityUpdater visibilityUpdater, IMessageDeleter messageDeleter,
- Uri queueUri, MessageAttributes messageAttributes)
- {
- Message = message;
- MessageType = messageType;
- QueueName = queueName;
- VisibilityUpdater = visibilityUpdater;
- MessageDeleter = messageDeleter;
- QueueUri = queueUri;
- MessageAttributes = messageAttributes;
- RawMessage = rawMessage;
- }
///
/// The queue name from which this message was received.
///
- public string QueueName { get; }
+ public string QueueName { get; } = queueName;
///
/// The type of the JustSaying message contained in .
///
- public Type MessageType { get; }
+ public Type MessageType { get; } = messageType;
///
/// The JustSaying message that was deserialized from SQS.
///
- public Message Message { get; }
+ public Message Message { get; } = message;
///
/// The Absolute Uri of the queue this message came from.
///
- public Uri QueueUri { get; }
+ public Uri QueueUri { get; } = queueUri;
///
/// A collection of attributes that were downloaded with this message.
///
- public MessageAttributes MessageAttributes { get; }
+ public MessageAttributes MessageAttributes { get; } = messageAttributes;
///
/// The raw SQS message that was downloaded from the queue.
///
- public Amazon.SQS.Model.Message RawMessage { get; }
+ public Amazon.SQS.Model.Message RawMessage { get; } = rawMessage;
///
/// An that can be used to update the visibility timeout for this message.
///
- public IMessageVisibilityUpdater VisibilityUpdater { get; }
+ public IMessageVisibilityUpdater VisibilityUpdater { get; } = visibilityUpdater;
///
/// An that can be used to delete this message.
///
- public IMessageDeleter MessageDeleter { get; }
+ public IMessageDeleter MessageDeleter { get; } = messageDeleter;
///
/// The that occurred in the handling of this message.
@@ -83,4 +78,4 @@ public void SetException(Exception e)
{
HandledException = e;
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Messaging/Middleware/Handle/HandlerInvocationMiddleware.cs b/src/JustSaying/Messaging/Middleware/Handle/HandlerInvocationMiddleware.cs
index 40cf73c70..ac6a0440f 100644
--- a/src/JustSaying/Messaging/Middleware/Handle/HandlerInvocationMiddleware.cs
+++ b/src/JustSaying/Messaging/Middleware/Handle/HandlerInvocationMiddleware.cs
@@ -8,14 +8,9 @@ namespace JustSaying.Messaging.Middleware;
/// This middleware is responsible for resolving a message handler and calling it.
///
/// The type of the message that the message handler handles.
-public sealed class HandlerInvocationMiddleware : MiddlewareBase where T : Message
+public sealed class HandlerInvocationMiddleware(Func> handlerResolver) : MiddlewareBase where T : Message
{
- private readonly Func> _handlerResolver;
-
- public HandlerInvocationMiddleware(Func> handlerResolver)
- {
- _handlerResolver = handlerResolver ?? throw new ArgumentNullException(nameof(handlerResolver));
- }
+ private readonly Func> _handlerResolver = handlerResolver ?? throw new ArgumentNullException(nameof(handlerResolver));
protected override async Task RunInnerAsync(
HandleMessageContext context,
@@ -32,4 +27,4 @@ protected override async Task RunInnerAsync(
return await handler.Handle(context.MessageAs()).ConfigureAwait(false);
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Messaging/Middleware/Handle/HandlerMiddlewareBuilder.cs b/src/JustSaying/Messaging/Middleware/Handle/HandlerMiddlewareBuilder.cs
index 58611914f..77c07c11b 100644
--- a/src/JustSaying/Messaging/Middleware/Handle/HandlerMiddlewareBuilder.cs
+++ b/src/JustSaying/Messaging/Middleware/Handle/HandlerMiddlewareBuilder.cs
@@ -9,28 +9,20 @@ namespace JustSaying.Messaging.Middleware;
///
/// A class representing a builder for a middleware pipeline.
///
-public sealed class HandlerMiddlewareBuilder
+///
+/// Creates a HandlerMiddlewareBuilder instance.
+///
+/// An that can create handlers.
+/// An that enables resolution of middlewares
+/// and middleware services.
+public sealed class HandlerMiddlewareBuilder(IHandlerResolver handlerResolver, IServiceResolver serviceResolver)
{
private Action _configure;
- internal IServiceResolver ServiceResolver { get; }
- private IHandlerResolver HandlerResolver { get; }
+ internal IServiceResolver ServiceResolver { get; } = serviceResolver;
- private readonly List> _middlewares;
+ private readonly List> _middlewares = [];
private HandleMessageMiddleware _handlerMiddleware;
- ///
- /// Creates a HandlerMiddlewareBuilder instance.
- ///
- /// An that can create handlers.
- /// An that enables resolution of middlewares
- /// and middleware services.
- public HandlerMiddlewareBuilder(IHandlerResolver handlerResolver, IServiceResolver serviceResolver)
- {
- ServiceResolver = serviceResolver;
- HandlerResolver = handlerResolver;
- _middlewares = new List>();
- }
-
///
/// Adds a middleware of type to the pipeline which will be resolved from the
/// . It will be resolved once when the pipeline is built, and cached
@@ -103,7 +95,7 @@ public HandlerMiddlewareBuilder UseHandler() where TMessage : Message
$"Handler middleware has already been specified for {typeof(TMessage).Name} on this queue.");
}
- _handlerMiddleware = new HandlerInvocationMiddleware(HandlerResolver.ResolveHandler);
+ _handlerMiddleware = new HandlerInvocationMiddleware(handlerResolver.ResolveHandler);
return this;
}
diff --git a/src/JustSaying/Messaging/Middleware/Handle/HandlerMiddlewareBuilderExtensions.cs b/src/JustSaying/Messaging/Middleware/Handle/HandlerMiddlewareBuilderExtensions.cs
index 0b633ff3b..2b03d39d8 100644
--- a/src/JustSaying/Messaging/Middleware/Handle/HandlerMiddlewareBuilderExtensions.cs
+++ b/src/JustSaying/Messaging/Middleware/Handle/HandlerMiddlewareBuilderExtensions.cs
@@ -5,7 +5,6 @@
using JustSaying.Messaging.Middleware.MessageContext;
using JustSaying.Messaging.Middleware.PostProcessing;
using JustSaying.Models;
-using HandleMessageMiddleware = JustSaying.Messaging.Middleware.MiddlewareBase;
// ReSharper disable once CheckNamespace
namespace JustSaying.Messaging.Middleware;
diff --git a/src/JustSaying/Messaging/Middleware/Logging/LoggingMiddleware.cs b/src/JustSaying/Messaging/Middleware/Logging/LoggingMiddleware.cs
index b6d37311e..ba513aa78 100644
--- a/src/JustSaying/Messaging/Middleware/Logging/LoggingMiddleware.cs
+++ b/src/JustSaying/Messaging/Middleware/Logging/LoggingMiddleware.cs
@@ -6,23 +6,15 @@ namespace JustSaying.Messaging.Middleware.Logging;
///
/// A middleware that logs a rich information or warning event when a message is handled.
///
-public sealed class LoggingMiddleware : MiddlewareBase
+///
+/// Constructs a .
+///
+/// The to write logs to.
+public sealed class LoggingMiddleware(ILoggerFactory loggerFactory) : MiddlewareBase
{
- private readonly ILogger _logger;
-
- ///
- /// Constructs a .
- ///
- /// The to write logs to.
- public LoggingMiddleware(ILoggerFactory loggerFactory)
- {
- _logger = loggerFactory?.CreateLogger() ??
- throw new ArgumentNullException(nameof(loggerFactory));
- }
-
- private const string MessageTemplate = "{Status} handling message with Id '{MessageId}' of type {MessageType} in {TimeToHandle}ms.";
- private const string Succeeded = nameof(Succeeded);
- private const string Failed = nameof(Failed);
+ private readonly ILogger _logger =
+ loggerFactory?.CreateLogger()
+ ?? throw new ArgumentNullException(nameof(loggerFactory));
protected override async Task RunInnerAsync(HandleMessageContext context, Func> func, CancellationToken stoppingToken)
{
@@ -42,18 +34,24 @@ protected override async Task RunInnerAsync(HandleMessageContext context,
}
finally
{
+ const string MessageTemplate = "{Status} handling message with Id '{MessageId}' of type {MessageType} in {TimeToHandle}ms.";
+
if (dispatchSuccessful)
{
- _logger.LogInformation(context.HandledException, MessageTemplate,
- Succeeded,
+ _logger.LogInformation(
+ context.HandledException,
+ MessageTemplate,
+ "Succeeded",
context.Message.Id,
context.MessageType.FullName,
watch.ElapsedMilliseconds);
}
else
{
- _logger.LogWarning(context.HandledException, MessageTemplate,
- Failed,
+ _logger.LogWarning(
+ context.HandledException,
+ MessageTemplate,
+ "Failed",
context.Message.Id,
context.MessageType.FullName,
watch.ElapsedMilliseconds);
diff --git a/src/JustSaying/Messaging/Middleware/MessageContext/MessageContextAccessorMiddleware.cs b/src/JustSaying/Messaging/Middleware/MessageContext/MessageContextAccessorMiddleware.cs
index 76357edd0..b3f4991c4 100644
--- a/src/JustSaying/Messaging/Middleware/MessageContext/MessageContextAccessorMiddleware.cs
+++ b/src/JustSaying/Messaging/Middleware/MessageContext/MessageContextAccessorMiddleware.cs
@@ -5,18 +5,13 @@ namespace JustSaying.Messaging.Middleware.MessageContext;
///
/// A middleware that sets context that is available in message handlers by resolving an `IMessageContextAccessor`.
///
-public sealed class MessageContextAccessorMiddleware : MiddlewareBase
+///
+/// Creates an instance of .
+///
+/// The to set.
+public sealed class MessageContextAccessorMiddleware(IMessageContextAccessor messageContextAccessor) : MiddlewareBase
{
- private readonly IMessageContextAccessor _messageContextAccessor;
-
- ///
- /// Creates an instance of .
- ///
- /// The to set.
- public MessageContextAccessorMiddleware(IMessageContextAccessor messageContextAccessor)
- {
- _messageContextAccessor = messageContextAccessor ?? throw new ArgumentNullException(nameof(messageContextAccessor));
- }
+ private readonly IMessageContextAccessor _messageContextAccessor = messageContextAccessor ?? throw new ArgumentNullException(nameof(messageContextAccessor));
protected override async Task RunInnerAsync(HandleMessageContext context, Func> func, CancellationToken stoppingToken)
{
@@ -31,4 +26,4 @@ protected override async Task RunInnerAsync(HandleMessageContext context,
_messageContextAccessor.MessageContext = null;
}
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Messaging/Middleware/Metrics/StopwatchMiddleware.cs b/src/JustSaying/Messaging/Middleware/Metrics/StopwatchMiddleware.cs
index 415377fcb..f62b66862 100644
--- a/src/JustSaying/Messaging/Middleware/Metrics/StopwatchMiddleware.cs
+++ b/src/JustSaying/Messaging/Middleware/Metrics/StopwatchMiddleware.cs
@@ -7,30 +7,21 @@ namespace JustSaying.Messaging.Middleware;
///
/// This middleware measures the handler's execution duration and reports the results to an .
///
-public sealed class StopwatchMiddleware : MiddlewareBase
+///
+/// Creates an instance of a that will report results to an
+/// .
+///
+/// An to report results to.
+/// The type of the handler that results should be reported against.
+public sealed class StopwatchMiddleware(IMessageMonitor monitor, Type handlerType) : MiddlewareBase
{
- private readonly IMessageMonitor _monitor;
- private readonly Type _handlerType;
-
- ///
- /// Creates an instance of a that will report results to an
- /// .
- ///
- /// An to report results to.
- /// The type of the handler that results should be reported against.
- public StopwatchMiddleware(IMessageMonitor monitor, Type handlerType)
- {
- _monitor = monitor;
- _handlerType = handlerType;
- }
-
protected override async Task RunInnerAsync(HandleMessageContext context, Func> func, CancellationToken stoppingToken)
{
var watch = Stopwatch.StartNew();
try
{
- using (_monitor.MeasureDispatch())
+ using (monitor.MeasureDispatch())
{
return await func(stoppingToken).ConfigureAwait(false);
}
@@ -38,7 +29,7 @@ protected override async Task RunInnerAsync(HandleMessageContext context,
finally
{
watch.Stop();
- _monitor.HandlerExecutionTime(_handlerType, context.MessageType, watch.Elapsed);
+ monitor.HandlerExecutionTime(handlerType, context.MessageType, watch.Elapsed);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Messaging/Middleware/MiddlewareBase`2.cs b/src/JustSaying/Messaging/Middleware/MiddlewareBase`2.cs
index 2dcd1d0e3..84aaa9411 100644
--- a/src/JustSaying/Messaging/Middleware/MiddlewareBase`2.cs
+++ b/src/JustSaying/Messaging/Middleware/MiddlewareBase`2.cs
@@ -32,7 +32,7 @@ public async Task RunAsync(
return await func(ct).ConfigureAwait(false);
}
- else return default(TOut);
+ else return default;
},
stoppingToken).ConfigureAwait(false);
}
diff --git a/src/JustSaying/Messaging/Middleware/Receive/DefaultReceiveMessagesMiddleware.cs b/src/JustSaying/Messaging/Middleware/Receive/DefaultReceiveMessagesMiddleware.cs
index 45109a217..6c634727d 100644
--- a/src/JustSaying/Messaging/Middleware/Receive/DefaultReceiveMessagesMiddleware.cs
+++ b/src/JustSaying/Messaging/Middleware/Receive/DefaultReceiveMessagesMiddleware.cs
@@ -6,19 +6,12 @@ namespace JustSaying.Messaging.Middleware.Receive;
///
/// The default middleware to use for the receive pipeline.
///
-public class DefaultReceiveMessagesMiddleware : MiddlewareBase>
+///
+/// Creates an instance of .
+///
+/// The to use.
+public class DefaultReceiveMessagesMiddleware(ILogger logger) : MiddlewareBase>
{
- private readonly ILogger _logger;
-
- ///
- /// Creates an instance of .
- ///
- /// The to use.
- public DefaultReceiveMessagesMiddleware(ILogger logger)
- {
- _logger = logger;
- }
-
protected override async Task> RunInnerAsync(
ReceiveMessagesContext context,
Func>> func,
@@ -28,7 +21,7 @@ protected override async Task> RunInnerAsync(
{
var results = await func(stoppingToken).ConfigureAwait(false);
- _logger.LogTrace(
+ logger.LogTrace(
"Polled for messages on queue '{QueueName}' in region '{Region}', and received {MessageCount} messages.",
context.QueueName,
context.RegionName,
@@ -38,7 +31,7 @@ protected override async Task> RunInnerAsync(
}
catch (OperationCanceledException ex)
{
- _logger.LogTrace(
+ logger.LogTrace(
ex,
"Request to get more messages from queue was canceled for queue '{QueueName}' in region '{Region}'," +
"likely because there are no messages in the queue. " +
@@ -46,11 +39,9 @@ protected override async Task> RunInnerAsync(
context.QueueName,
context.RegionName);
}
-#pragma warning disable CA1031
catch (Exception ex)
-#pragma warning restore CA1031
{
- _logger.LogError(
+ logger.LogError(
ex,
"Error receiving messages on queue '{QueueName}' in region '{Region}'.",
context.QueueName,
@@ -59,4 +50,4 @@ protected override async Task> RunInnerAsync(
return Array.Empty();
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/Messaging/Monitoring/LogOperation.cs b/src/JustSaying/Messaging/Monitoring/LogOperation.cs
index 16d11e251..c30ce0d0e 100644
--- a/src/JustSaying/Messaging/Monitoring/LogOperation.cs
+++ b/src/JustSaying/Messaging/Monitoring/LogOperation.cs
@@ -3,54 +3,45 @@
namespace JustSaying.Messaging.Monitoring;
-internal sealed class LogOperation : IDisposable
+internal sealed class LogOperation(ILogger logger, LogLevel logLevel, string message, params object[] args) : IDisposable
{
- private readonly ILogger _logger;
- private readonly string _message;
- private readonly object[] _args;
- private readonly Stopwatch _watch;
- private readonly LogLevel _logLevel;
-
- private const string MessageTemplate = " finished in {0:0}ms";
-
- public LogOperation(ILogger logger, LogLevel logLevel, string message, params object[] args)
- {
- _logger = logger;
- _logLevel = logLevel;
- _message = message;
- _args = args;
- _watch = Stopwatch.StartNew();
- }
+ private readonly string _message = message;
+ private readonly object[] _args = args;
+ private readonly Stopwatch _watch = Stopwatch.StartNew();
public void Dispose()
{
_watch.Stop();
- var message = $"{_message}{MessageTemplate}";
- var args = _args.Concat(new object[] { _watch.Elapsed.TotalMilliseconds }).ToArray();
+ var message = $"{_message} finished in {0:0}ms";
+ var args = _args.Concat([_watch.Elapsed.TotalMilliseconds]).ToArray();
- switch (_logLevel)
+#pragma warning disable CA2254
+ switch (logLevel)
{
case LogLevel.Trace:
- _logger.LogTrace(message, args);
+ logger.LogTrace(message, args);
return;
case LogLevel.Debug:
- _logger.LogDebug(message, args);
+ logger.LogDebug(message, args);
return;
case LogLevel.Information:
- _logger.LogInformation(message, args);
+ logger.LogInformation(message, args);
return;
case LogLevel.Warning:
- _logger.LogWarning(message, args);
+ logger.LogWarning(message, args);
return;
case LogLevel.Error:
- _logger.LogError(message, args);
+ logger.LogError(message, args);
return;
case LogLevel.Critical:
- _logger.LogCritical(message, args);
+ logger.LogCritical(message, args);
return;
case LogLevel.None:
return;
+ default:
+ break;
}
+#pragma warning restore CA2254
}
}
diff --git a/src/JustSaying/Messaging/Monitoring/MonitorExtensions.cs b/src/JustSaying/Messaging/Monitoring/MonitorExtensions.cs
index bc5fc6252..6919cd773 100644
--- a/src/JustSaying/Messaging/Monitoring/MonitorExtensions.cs
+++ b/src/JustSaying/Messaging/Monitoring/MonitorExtensions.cs
@@ -3,7 +3,7 @@ namespace JustSaying.Messaging.Monitoring;
internal static class MonitorExtensions
{
public static Operation MeasureThrottle(this IMessageMonitor messageMonitor)
- => new Operation(messageMonitor, (duration, monitor) =>
+ => new(messageMonitor, (duration, monitor) =>
{
if (duration.TotalMilliseconds < 1) return;
monitor.IncrementThrottlingStatistic();
@@ -11,12 +11,12 @@ public static Operation MeasureThrottle(this IMessageMonitor messageMonitor)
});
public static Operation MeasureDispatch(this IMessageMonitor messageMonitor)
- => new Operation(messageMonitor, (duration, monitor) => monitor.HandleTime(duration));
+ => new(messageMonitor, (duration, monitor) => monitor.HandleTime(duration));
public static Operation MeasureReceive(this IMessageMonitor messageMonitor, string queueName, string region)
- => new Operation(messageMonitor,
+ => new(messageMonitor,
(duration, monitor) => monitor.ReceiveMessageTime(duration, queueName, region));
public static Operation MeasurePublish(this IMessageMonitor messageMonitor)
- => new Operation(messageMonitor, (duration, monitor) => monitor.PublishMessageTime(duration));
-}
\ No newline at end of file
+ => new(messageMonitor, (duration, monitor) => monitor.PublishMessageTime(duration));
+}
diff --git a/src/JustSaying/Messaging/PublishMetadata.cs b/src/JustSaying/Messaging/PublishMetadata.cs
index e800da5af..cde53e33a 100644
--- a/src/JustSaying/Messaging/PublishMetadata.cs
+++ b/src/JustSaying/Messaging/PublishMetadata.cs
@@ -10,14 +10,11 @@ public class PublishMetadata
public PublishMetadata AddMessageAttribute(string key, IReadOnlyCollection data)
{
- if (data == null)
+ var mav = new MessageAttributeValue
{
- throw new ArgumentNullException(nameof(data));
- }
-
- var mav = new MessageAttributeValue();
- mav.BinaryValue = data;
- mav.DataType = "Binary";
+ BinaryValue = data ?? throw new ArgumentNullException(nameof(data)),
+ DataType = "Binary"
+ };
MessageAttributes[key] = mav;
@@ -26,10 +23,7 @@ public PublishMetadata AddMessageAttribute(string key, IReadOnlyCollection
public PublishMetadata AddMessageAttribute(string key, MessageAttributeValue value)
{
- if (MessageAttributes == null)
- {
- MessageAttributes = new Dictionary(StringComparer.Ordinal);
- }
+ MessageAttributes ??= new Dictionary(StringComparer.Ordinal);
MessageAttributes[key] = value;
@@ -54,4 +48,4 @@ public PublishMetadata AddMessageAttribute(string key, double value)
});
}
-}
\ No newline at end of file
+}
diff --git a/src/JustSaying/MessagingBusBuilder.cs b/src/JustSaying/MessagingBusBuilder.cs
index 5c958a5b6..b7b77c52e 100644
--- a/src/JustSaying/MessagingBusBuilder.cs
+++ b/src/JustSaying/MessagingBusBuilder.cs
@@ -79,10 +79,7 @@ public MessagingBusBuilder Client(Action configure)
throw new ArgumentNullException(nameof(configure));
}
- if (ClientFactoryBuilder == null)
- {
- ClientFactoryBuilder = new AwsClientFactoryBuilder(this);
- }
+ ClientFactoryBuilder ??= new AwsClientFactoryBuilder(this);
configure(ClientFactoryBuilder);
@@ -106,10 +103,7 @@ public MessagingBusBuilder Messaging(Action confi
throw new ArgumentNullException(nameof(configure));
}
- if (MessagingConfig == null)
- {
- MessagingConfig = new MessagingConfigurationBuilder(this);
- }
+ MessagingConfig ??= new MessagingConfigurationBuilder(this);
configure(MessagingConfig);
@@ -133,10 +127,7 @@ public MessagingBusBuilder Publications(Action configure)
throw new ArgumentNullException(nameof(configure));
}
- if (PublicationsBuilder == null)
- {
- PublicationsBuilder = new PublicationsBuilder(this);
- }
+ PublicationsBuilder ??= new PublicationsBuilder(this);
configure(PublicationsBuilder);
@@ -233,10 +224,7 @@ public IMessagePublisher BuildPublisher()
JustSayingBus bus = CreateBus(config, loggerFactory);
IAwsClientFactoryProxy proxy = CreateFactoryProxy();
- if (PublicationsBuilder != null)
- {
- PublicationsBuilder.Configure(bus, proxy, loggerFactory);
- }
+ PublicationsBuilder?.Configure(bus, proxy, loggerFactory);
return bus;
}
diff --git a/src/JustSaying/Naming/DefaultNamingConventions.cs b/src/JustSaying/Naming/DefaultNamingConventions.cs
index b84f044ba..8eb9fbd89 100644
--- a/src/JustSaying/Naming/DefaultNamingConventions.cs
+++ b/src/JustSaying/Naming/DefaultNamingConventions.cs
@@ -8,10 +8,7 @@ namespace JustSaying.Naming;
///
public class DefaultNamingConventions : ITopicNamingConvention, IQueueNamingConvention
{
- private const int MaxTopicNameLength = 256;
- private const int MaxQueueNameLength = 80;
-
- private static readonly HashSet TypesToMapAutomatically = new HashSet
+ private static readonly HashSet TypesToMapAutomatically = new()
{
typeof(string),
typeof(object),
@@ -34,9 +31,9 @@ public class DefaultNamingConventions : ITopicNamingConvention, IQueueNamingConv
typeof(DateTimeOffset)
};
- public virtual string TopicName() => CreateResourceName(typeof(T), MaxTopicNameLength);
+ public virtual string TopicName() => CreateResourceName(typeof(T), maximumLength: 256);
- public virtual string QueueName() => CreateResourceName(typeof(T), MaxQueueNameLength);
+ public virtual string QueueName() => CreateResourceName(typeof(T), maximumLength: 80);
private static string CreateResourceName(Type type, int maximumLength)
{
@@ -73,4 +70,4 @@ private static string GetTypeFriendlyName(Type type)
return friendlyName;
}
-}
\ No newline at end of file
+}
diff --git a/tests/JustSaying.Benchmark/BenchmarkMessage.cs b/tests/JustSaying.Benchmark/BenchmarkMessage.cs
index efd9b13ea..26c2afda4 100644
--- a/tests/JustSaying.Benchmark/BenchmarkMessage.cs
+++ b/tests/JustSaying.Benchmark/BenchmarkMessage.cs
@@ -2,14 +2,8 @@
namespace JustSaying.Benchmark;
-public class BenchmarkMessage : Message
+public class BenchmarkMessage(TimeSpan sentAtOffset, int sequenceId) : Message
{
- public BenchmarkMessage(TimeSpan sentAtOffset, int sequenceId)
- {
- SentAtOffset = sentAtOffset;
- SequenceId = sequenceId;
- }
-
- public TimeSpan SentAtOffset { get; }
- public int SequenceId { get; }
-}
\ No newline at end of file
+ public TimeSpan SentAtOffset { get; } = sentAtOffset;
+ public int SequenceId { get; } = sequenceId;
+}
diff --git a/tests/JustSaying.Benchmark/BenchmarkMessageHander.cs b/tests/JustSaying.Benchmark/BenchmarkMessageHander.cs
index 418252fae..9cece764e 100644
--- a/tests/JustSaying.Benchmark/BenchmarkMessageHander.cs
+++ b/tests/JustSaying.Benchmark/BenchmarkMessageHander.cs
@@ -2,18 +2,13 @@
namespace JustSaying.Benchmark;
-public class BenchmarkMessageHander : IHandlerAsync
+public class BenchmarkMessageHander(IReportConsumerMetric reporter) : IHandlerAsync
{
- private readonly IReportConsumerMetric _reporter;
-
- public BenchmarkMessageHander(IReportConsumerMetric reporter)
- {
- _reporter = reporter;
- }
+ private readonly IReportConsumerMetric _reporter = reporter;
public Task Handle(BenchmarkMessage message)
{
_reporter.Consumed(message.Id);
return Task.FromResult(true);
}
-}
\ No newline at end of file
+}
diff --git a/tests/JustSaying.Benchmark/JustSayingBenchmark.cs b/tests/JustSaying.Benchmark/JustSayingBenchmark.cs
index f5fdf4609..a7d102a01 100644
--- a/tests/JustSaying.Benchmark/JustSayingBenchmark.cs
+++ b/tests/JustSaying.Benchmark/JustSayingBenchmark.cs
@@ -99,7 +99,7 @@ public static async Task RunTest(JustSayingBenchmark options)
DrawResponseTimeGraph(messageMetrics, m => m.ConsumeLatency);
}
- static void RegisterJustSaying(IServiceCollection services)
+ private static void RegisterJustSaying(IServiceCollection services)
{
services.AddJustSaying(config =>
{
@@ -113,7 +113,7 @@ static void RegisterJustSaying(IServiceCollection services)
services.AddJustSayingHandler();
}
- static void DrawResponseTimeGraph(MessageMetric[] metrics, Func selector)
+ private static void DrawResponseTimeGraph(MessageMetric[] metrics, Func selector)
{
long maxTime = metrics.Max(selector);
long minTime = metrics.Min(selector);
@@ -143,4 +143,4 @@ orderby segment.Key
new string('*', barLength));
}
}
-}
\ No newline at end of file
+}
diff --git a/tests/JustSaying.Benchmark/MessageMetric.cs b/tests/JustSaying.Benchmark/MessageMetric.cs
index 4435fa2f4..93dc9357e 100644
--- a/tests/JustSaying.Benchmark/MessageMetric.cs
+++ b/tests/JustSaying.Benchmark/MessageMetric.cs
@@ -1,15 +1,8 @@
namespace JustSaying.Benchmark;
-public class MessageMetric
+public class MessageMetric(Guid messageId, long ackLatency, long consumeLatency)
{
- public MessageMetric(Guid messageId, long ackLatency, long consumeLatency)
- {
- MessageId = messageId;
- AckLatency = ackLatency;
- ConsumeLatency = consumeLatency;
- }
-
- public Guid MessageId { get; }
- public long AckLatency { get; set; }
- public long ConsumeLatency { get; set; }
-}
\ No newline at end of file
+ public Guid MessageId { get; } = messageId;
+ public long AckLatency { get; set; } = ackLatency;
+ public long ConsumeLatency { get; set; } = consumeLatency;
+}
diff --git a/tests/JustSaying.Benchmark/MessageMetricCapture.cs b/tests/JustSaying.Benchmark/MessageMetricCapture.cs
index 9ba514333..d157813e2 100644
--- a/tests/JustSaying.Benchmark/MessageMetricCapture.cs
+++ b/tests/JustSaying.Benchmark/MessageMetricCapture.cs
@@ -4,29 +4,15 @@
namespace JustSaying.Benchmark;
// Borrowed with ❤ from https://github.com/MassTransit/MassTransit-Benchmark/blob/a04a0235e1/src/MassTransit-Benchmark/Latency/MessageMetricCapture.cs
-public class MessageMetricCapture :
- IReportConsumerMetric
+public class MessageMetricCapture(long messageCount) : IReportConsumerMetric
{
- readonly TaskCompletionSource _consumeCompleted;
- readonly ConcurrentBag _consumedMessages;
- readonly long _messageCount;
- readonly TaskCompletionSource _sendCompleted;
- readonly ConcurrentBag _sentMessages;
- readonly Stopwatch _stopwatch;
- long _consumed;
- long _sent;
-
- public MessageMetricCapture(long messageCount)
- {
- _messageCount = messageCount;
-
- _consumedMessages = new ConcurrentBag();
- _sentMessages = new ConcurrentBag();
- _sendCompleted = new TaskCompletionSource();
- _consumeCompleted = new TaskCompletionSource();
-
- _stopwatch = Stopwatch.StartNew();
- }
+ private readonly TaskCompletionSource _consumeCompleted = new();
+ private readonly ConcurrentBag _consumedMessages = [];
+ private readonly TaskCompletionSource _sendCompleted = new();
+ private readonly ConcurrentBag _sentMessages = [];
+ private readonly Stopwatch _stopwatch = Stopwatch.StartNew();
+ private long _consumed;
+ private long _sent;
public Task SendCompleted => _sendCompleted.Task;
public Task ConsumeCompleted => _consumeCompleted.Task;
@@ -36,7 +22,7 @@ Task IReportConsumerMetric.Consumed(Guid messageId)
_consumedMessages.Add(new ConsumedMessage(messageId, _stopwatch.ElapsedTicks));
long consumed = Interlocked.Increment(ref _consumed);
- if (consumed == _messageCount)
+ if (consumed == messageCount)
_consumeCompleted.TrySetResult(_stopwatch.Elapsed);
return Task.CompletedTask;
@@ -53,7 +39,7 @@ public async Task Sent(Guid messageId, Task sendTask)
_sentMessages.Add(new SentMessage(messageId, sendTimestamp, ackTimestamp));
long sent = Interlocked.Increment(ref _sent);
- if (sent == _messageCount)
+ if (sent == messageCount)
_sendCompleted.TrySetResult(_stopwatch.Elapsed);
}
@@ -69,31 +55,16 @@ public MessageMetric[] GetMessageMetrics()
.ToArray();
}
-
- struct SentMessage
+ private readonly struct SentMessage(Guid messageId, long sendTimestamp, long ackTimestamp)
{
- public readonly Guid MessageId;
- public readonly long SendTimestamp;
- public readonly long AckTimestamp;
-
- public SentMessage(Guid messageId, long sendTimestamp, long ackTimestamp)
- {
- MessageId = messageId;
- SendTimestamp = sendTimestamp;
- AckTimestamp = ackTimestamp;
- }
+ public readonly Guid MessageId = messageId;
+ public readonly long SendTimestamp = sendTimestamp;
+ public readonly long AckTimestamp = ackTimestamp;
}
-
- struct ConsumedMessage
+ private readonly struct ConsumedMessage(Guid messageId, long timestamp)
{
- public readonly Guid MessageId;
- public readonly long Timestamp;
-
- public ConsumedMessage(Guid messageId, long timestamp)
- {
- MessageId = messageId;
- Timestamp = timestamp;
- }
+ public readonly Guid MessageId = messageId;
+ public readonly long Timestamp = timestamp;
}
-}
\ No newline at end of file
+}
diff --git a/tests/JustSaying.Extensions.DependencyInjection.StructureMap.Tests/StructureMapTests.cs b/tests/JustSaying.Extensions.DependencyInjection.StructureMap.Tests/StructureMapTests.cs
index f13b80aa3..1a7a2ee25 100644
--- a/tests/JustSaying.Extensions.DependencyInjection.StructureMap.Tests/StructureMapTests.cs
+++ b/tests/JustSaying.Extensions.DependencyInjection.StructureMap.Tests/StructureMapTests.cs
@@ -8,14 +8,9 @@
namespace JustSaying;
-public class WhenUsingStructureMap
+public class WhenUsingStructureMap(ITestOutputHelper outputHelper)
{
- public WhenUsingStructureMap(ITestOutputHelper outputHelper)
- {
- OutputHelper = outputHelper;
- }
-
- private ITestOutputHelper OutputHelper { get; }
+ private ITestOutputHelper OutputHelper { get; } = outputHelper;
[AwsFact]
public async Task Can_Create_Messaging_Bus_Fluently_For_A_Queue()
diff --git a/tests/JustSaying.IntegrationTests/Fluent/ActionRunnerTest.cs b/tests/JustSaying.IntegrationTests/Fluent/ActionRunnerTest.cs
index 5cd929ac2..71456f9e1 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/ActionRunnerTest.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/ActionRunnerTest.cs
@@ -1,17 +1,13 @@
namespace JustSaying.IntegrationTests.Fluent;
-public class ActionRunnerTest : IntegrationTestBase
+public class ActionRunnerTest(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public ActionRunnerTest(ITestOutputHelper outputHelper) : base(outputHelper)
- {
- }
-
protected override TimeSpan Timeout => TimeSpan.FromSeconds(2);
[Fact]
public async Task TestRunnerWillSucceedOnSuccessfulTask()
{
- async Task SuccessTask(CancellationToken ctx) =>
+ static async Task SuccessTask(CancellationToken ctx) =>
await Task.Delay(100, ctx);
await RunActionWithTimeout(SuccessTask);
@@ -30,7 +26,7 @@ await Assert.ThrowsAsync(
[Fact]
public async Task TestRunnerWillThrowOnFailure()
{
- async Task ThrowingTask(CancellationToken ctx)
+ static async Task ThrowingTask(CancellationToken ctx)
{
await Task.Delay(100, ctx);
throw new InvalidOperationException();
diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenANamedQueueIsCreated.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenANamedQueueIsCreated.cs
index be9342d15..1be2eb7b4 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenANamedQueueIsCreated.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenANamedQueueIsCreated.cs
@@ -8,13 +8,8 @@
namespace JustSaying.IntegrationTests.Fluent.AwsTools;
-public class WhenANamedQueueIsCreated : IntegrationTestBase
+public class WhenANamedQueueIsCreated(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenANamedQueueIsCreated(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_The_Error_Queue_Is_Created()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingAQueueWithNoErrorQueue.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingAQueueWithNoErrorQueue.cs
index dd1ec61fb..ddbfa64ca 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingAQueueWithNoErrorQueue.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingAQueueWithNoErrorQueue.cs
@@ -8,13 +8,8 @@
namespace JustSaying.IntegrationTests.Fluent.AwsTools;
-public class WhenCreatingAQueueWithNoErrorQueue : IntegrationTestBase
+public class WhenCreatingAQueueWithNoErrorQueue(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenCreatingAQueueWithNoErrorQueue(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_The_Error_Queue_Is_Not_Created()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingErrorQueue.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingErrorQueue.cs
index e64277b06..541caf414 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingErrorQueue.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingErrorQueue.cs
@@ -7,13 +7,8 @@
namespace JustSaying.IntegrationTests.Fluent.AwsTools;
-public class WhenCreatingErrorQueue : IntegrationTestBase
+public class WhenCreatingErrorQueue(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenCreatingErrorQueue(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_The_Message_Retention_Period_Is_Updated()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingQueueTwice.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingQueueTwice.cs
index 76bdc3865..433a8b7f6 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingQueueTwice.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingQueueTwice.cs
@@ -7,13 +7,8 @@
namespace JustSaying.IntegrationTests.Fluent.AwsTools;
-public class WhenCreatingQueueTwice : IntegrationTestBase
+public class WhenCreatingQueueTwice(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenCreatingQueueTwice(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_An_Exception_Is_Not_Thrown()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingTopicWithServerSideEncryption.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingTopicWithServerSideEncryption.cs
index d0997c519..e404c22ff 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingTopicWithServerSideEncryption.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenCreatingTopicWithServerSideEncryption.cs
@@ -7,13 +7,8 @@
namespace JustSaying.IntegrationTests.Fluent.AwsTools;
-public class WhenCreatingTopicWithServerSideEncryption : IntegrationTestBase
+public class WhenCreatingTopicWithServerSideEncryption(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenCreatingTopicWithServerSideEncryption(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[NotSimulatorFact]
public async Task Can_Create_Topic_With_Encryption()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenQueueIsDeleted.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenQueueIsDeleted.cs
index 0d70fe4eb..c71b2130a 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenQueueIsDeleted.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenQueueIsDeleted.cs
@@ -8,13 +8,8 @@
namespace JustSaying.IntegrationTests.Fluent.AwsTools;
-public class WhenQueueIsDeleted : IntegrationTestBase
+public class WhenQueueIsDeleted(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenQueueIsDeleted(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_The_Error_Queue_Is_Deleted()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenRemovingServerSideEncryption.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenRemovingServerSideEncryption.cs
index 6b35f81c6..0ab8e1fe4 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenRemovingServerSideEncryption.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenRemovingServerSideEncryption.cs
@@ -7,13 +7,8 @@
namespace JustSaying.IntegrationTests.Fluent.AwsTools;
-public class WhenRemovingServerSideEncryption : IntegrationTestBase
+public class WhenRemovingServerSideEncryption(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenRemovingServerSideEncryption(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[NotSimulatorFact]
public async Task Can_Remove_Encryption()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenRemovingSnsServerSideEncryption.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenRemovingSnsServerSideEncryption.cs
index 18b268312..1edf876aa 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenRemovingSnsServerSideEncryption.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenRemovingSnsServerSideEncryption.cs
@@ -7,13 +7,8 @@
namespace JustSaying.IntegrationTests.Fluent.AwsTools;
-public class WhenRemovingSnsServerSideEncryption : IntegrationTestBase
+public class WhenRemovingSnsServerSideEncryption(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenRemovingSnsServerSideEncryption(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[NotSimulatorFact]
public async Task Can_Remove_Encryption()
{
@@ -31,9 +26,9 @@ public async Task Can_Remove_Encryption()
await topic.CreateWithEncryptionAsync(new ServerSideEncryption { KmsMasterKeyId = JustSayingConstants.DefaultSnsAttributeEncryptionKeyId }, CancellationToken.None);
// Act
- await topic.CreateWithEncryptionAsync(new ServerSideEncryption { KmsMasterKeyId = String.Empty }, CancellationToken.None);
+ await topic.CreateWithEncryptionAsync(new ServerSideEncryption { KmsMasterKeyId = string.Empty }, CancellationToken.None);
// Assert
topic.ServerSideEncryption.ShouldBeNull();
}
-}
\ No newline at end of file
+}
diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingDeliveryDelay.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingDeliveryDelay.cs
index ea1de85b5..c7a31cda4 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingDeliveryDelay.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingDeliveryDelay.cs
@@ -8,13 +8,8 @@
namespace JustSaying.IntegrationTests.Fluent.AwsTools;
-public class WhenUpdatingDeliveryDelay : IntegrationTestBase
+public class WhenUpdatingDeliveryDelay(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenUpdatingDeliveryDelay(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Can_Update_Delivery_Delay()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingRedrivePolicy.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingRedrivePolicy.cs
index ca1e83c34..f301af89c 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingRedrivePolicy.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingRedrivePolicy.cs
@@ -8,13 +8,8 @@
namespace JustSaying.IntegrationTests.Fluent.AwsTools;
-public class WhenUpdatingRedrivePolicy : IntegrationTestBase
+public class WhenUpdatingRedrivePolicy(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenUpdatingRedrivePolicy(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Can_Update_Redrive_Policy()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingRetentionPeriod.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingRetentionPeriod.cs
index c10554f77..a5a8bbc13 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingRetentionPeriod.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUpdatingRetentionPeriod.cs
@@ -8,13 +8,8 @@
namespace JustSaying.IntegrationTests.Fluent.AwsTools;
-public class WhenUpdatingRetentionPeriod : IntegrationTestBase
+public class WhenUpdatingRetentionPeriod(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenUpdatingRetentionPeriod(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Can_Update_Retention_Period()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingABasicThrottle.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingABasicThrottle.cs
index d0fdcbb92..5320d65e2 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingABasicThrottle.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingABasicThrottle.cs
@@ -13,13 +13,8 @@
namespace JustSaying.IntegrationTests.Fluent.AwsTools;
-public class WhenUsingABasicThrottle : IntegrationTestBase
+public class WhenUsingABasicThrottle(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenUsingABasicThrottle(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
protected override TimeSpan Timeout => TimeSpan.FromMinutes(5);
[AwsTheory]
diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingServerSideEncryption.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingServerSideEncryption.cs
index 3cf5cf99a..054e36f94 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingServerSideEncryption.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingServerSideEncryption.cs
@@ -4,13 +4,8 @@
namespace JustSaying.IntegrationTests.Fluent.AwsTools;
-public class WhenUsingServerSideEncryption : IntegrationTestBase
+public class WhenUsingServerSideEncryption(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenUsingServerSideEncryption(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_The_Message_Is_Handled()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingSnsServerSideEncryption.cs b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingSnsServerSideEncryption.cs
index 9b9145c08..3f5e8c75d 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingSnsServerSideEncryption.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/AwsTools/WhenUsingSnsServerSideEncryption.cs
@@ -6,13 +6,8 @@
namespace JustSaying.IntegrationTests.Fluent.AwsTools;
-public class WhenUsingSnsServerSideEncryption : IntegrationTestBase
+public class WhenUsingSnsServerSideEncryption(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenUsingSnsServerSideEncryption(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[NotSimulatorFact]
public async Task Then_The_Message_Is_Published()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Configuration/WhenUsingACustomSubjectProvider.cs b/tests/JustSaying.IntegrationTests/Fluent/Configuration/WhenUsingACustomSubjectProvider.cs
index 1492c5faa..e7edf59c9 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Configuration/WhenUsingACustomSubjectProvider.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Configuration/WhenUsingACustomSubjectProvider.cs
@@ -8,11 +8,8 @@
namespace JustSaying.Fluent.Configuration;
-public class WhenUsingACustomSubjectProvider : IntegrationTestBase
+public class WhenUsingACustomSubjectProvider(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenUsingACustomSubjectProvider(ITestOutputHelper outputHelper) : base(outputHelper)
- { }
-
[AwsFact]
public async Task ThenItIsUsed()
{
@@ -66,14 +63,9 @@ await Patiently.AssertThatAsync(OutputHelper,
});
}
- public class ConstantSubjectProvider : IMessageSubjectProvider
+ public class ConstantSubjectProvider(string subject) : IMessageSubjectProvider
{
- private readonly string _subject;
-
- public ConstantSubjectProvider(string subject)
- {
- _subject = subject;
- }
+ private readonly string _subject = subject;
public string GetSubjectForType(Type messageType)
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Configuration/WhenUsingNamingConventions.cs b/tests/JustSaying.IntegrationTests/Fluent/Configuration/WhenUsingNamingConventions.cs
index dc3380601..9c025281c 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Configuration/WhenUsingNamingConventions.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Configuration/WhenUsingNamingConventions.cs
@@ -7,12 +7,9 @@
namespace JustSaying.Fluent.Configuration;
-public class WhenUsingNamingConventions : IntegrationTestBase
+public class WhenUsingNamingConventions(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenUsingNamingConventions(ITestOutputHelper outputHelper) : base(outputHelper)
- { }
-
- class TestNamingConvention : ITopicNamingConvention, IQueueNamingConvention
+ private class TestNamingConvention : ITopicNamingConvention, IQueueNamingConvention
{
private readonly DefaultNamingConventions _default;
@@ -32,7 +29,7 @@ public string QueueName()
}
}
- [Fact]
+ [AwsFact]
public async Task ThenTheNamingConventionIsApplied()
{
var services = GivenJustSaying()
diff --git a/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringAHandlerViaContainerWithMissingRegistration.cs b/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringAHandlerViaContainerWithMissingRegistration.cs
index 22c9af65b..07ab91dfc 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringAHandlerViaContainerWithMissingRegistration.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringAHandlerViaContainerWithMissingRegistration.cs
@@ -4,13 +4,8 @@
namespace JustSaying.IntegrationTests.Fluent.DependencyInjection.Microsoft;
-public class WhenRegisteringAHandlerViaContainerWithMissingRegistration : IntegrationTestBase
+public class WhenRegisteringAHandlerViaContainerWithMissingRegistration(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenRegisteringAHandlerViaContainerWithMissingRegistration(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public void Then_An_Exception_Is_Thrown()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringASingleHandlerViaContainer.cs b/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringASingleHandlerViaContainer.cs
index fda667862..784394eda 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringASingleHandlerViaContainer.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringASingleHandlerViaContainer.cs
@@ -5,13 +5,8 @@
namespace JustSaying.IntegrationTests.Fluent.DependencyInjection.Microsoft;
-public class WhenRegisteringASingleHandlerViaContainer : IntegrationTestBase
+public class WhenRegisteringASingleHandlerViaContainer(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenRegisteringASingleHandlerViaContainer(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_The_Handler_Is_Resolved()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringMultipleHandlersViaContainer.cs b/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringMultipleHandlersViaContainer.cs
index b1f3c5311..c0e36c408 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringMultipleHandlersViaContainer.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenRegisteringMultipleHandlersViaContainer.cs
@@ -5,13 +5,8 @@
namespace JustSaying.IntegrationTests.Fluent.DependencyInjection.Microsoft;
-public class WhenRegisteringMultipleHandlersViaContainer : IntegrationTestBase
+public class WhenRegisteringMultipleHandlersViaContainer(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenRegisteringMultipleHandlersViaContainer(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public void Then_An_Exception_Is_Thrown()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenUsingCustomHandlerResolver.cs b/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenUsingCustomHandlerResolver.cs
index 86f1fc90b..3022ff490 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenUsingCustomHandlerResolver.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/DependencyInjection/Microsoft/WhenUsingCustomHandlerResolver.cs
@@ -5,13 +5,8 @@
namespace JustSaying.IntegrationTests.Fluent.DependencyInjection.Microsoft;
-public class WhenUsingCustomHandlerResolver : IntegrationTestBase
+public class WhenUsingCustomHandlerResolver(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenUsingCustomHandlerResolver(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_The_Handler_Is_Resolved_From_The_Custom_Resolver()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/IntegrationTestBase.cs b/tests/JustSaying.IntegrationTests/Fluent/IntegrationTestBase.cs
index 8cc88e44e..6fdd0f6fa 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/IntegrationTestBase.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/IntegrationTestBase.cs
@@ -11,22 +11,17 @@
namespace JustSaying.IntegrationTests.Fluent;
-public abstract class IntegrationTestBase
+public abstract class IntegrationTestBase(ITestOutputHelper outputHelper)
{
- protected IntegrationTestBase(ITestOutputHelper outputHelper)
- {
- OutputHelper = outputHelper;
- LoggerFactory = Microsoft.Extensions.Logging.LoggerFactory.Create(lf => lf.AddXUnit(outputHelper));
- }
-
protected virtual string AccessKeyId { get; } = "accessKeyId";
protected virtual string SecretAccessKey { get; } = "secretAccessKey";
protected virtual string SessionToken { get; } = "token";
- protected ITestOutputHelper OutputHelper { get; }
- protected ILoggerFactory LoggerFactory { get; }
+ protected ITestOutputHelper OutputHelper { get; } = outputHelper;
+
+ protected ILoggerFactory LoggerFactory { get; } = Microsoft.Extensions.Logging.LoggerFactory.Create(lf => lf.AddXUnit(outputHelper));
protected virtual string RegionName => Region.SystemName;
@@ -116,25 +111,23 @@ await action(publisher, listener, serviceProvider, cancellationToken)
protected async Task RunActionWithTimeout(Func action)
{
// See https://speakerdeck.com/davidfowl/scaling-asp-dot-net-core-applications?slide=28
- using (var cts = new CancellationTokenSource())
+ using var cts = new CancellationTokenSource();
+ var delayTask = Task.Delay(Timeout, cts.Token);
+ var actionTask = action(cts.Token);
+
+ var resultTask = await Task.WhenAny(actionTask, delayTask)
+ .ConfigureAwait(false);
+
+ if (resultTask == delayTask)
+ {
+ throw new TimeoutException(
+ $"The tested action took longer than the timeout of {Timeout} to complete.");
+ }
+ else
{
- var delayTask = Task.Delay(Timeout, cts.Token);
- var actionTask = action(cts.Token);
-
- var resultTask = await Task.WhenAny(actionTask, delayTask)
- .ConfigureAwait(false);
-
- if (resultTask == delayTask)
- {
- throw new TimeoutException(
- $"The tested action took longer than the timeout of {Timeout} to complete.");
- }
- else
- {
- cts.Cancel();
- }
-
- await actionTask;
+ cts.Cancel();
}
+
+ await actionTask;
}
}
diff --git a/tests/JustSaying.IntegrationTests/Fluent/MessagingBusBuilderTests.cs b/tests/JustSaying.IntegrationTests/Fluent/MessagingBusBuilderTests.cs
index 3f108b075..f75649baa 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/MessagingBusBuilderTests.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/MessagingBusBuilderTests.cs
@@ -8,19 +8,12 @@
namespace JustSaying.IntegrationTests;
-public class MessagingBusBuilderTests
+public class MessagingBusBuilderTests(ITestOutputHelper outputHelper)
{
- public MessagingBusBuilderTests(ITestOutputHelper outputHelper)
- {
- OutputHelper = outputHelper;
- }
-
- private ITestOutputHelper OutputHelper { get; }
+ private ITestOutputHelper OutputHelper { get; } = outputHelper;
- private class QueueStore : TestMessageStore
+ private class QueueStore(ILogger> logger) : TestMessageStore(logger)
{
- public QueueStore(ILogger> logger) : base(logger)
- { }
}
[AwsFact]
@@ -94,21 +87,20 @@ public async Task Can_Create_Messaging_Bus_Fluently_For_A_Topic()
IMessagePublisher publisher = serviceProvider.GetRequiredService();
IMessagingBus listener = serviceProvider.GetRequiredService();
- using (var source = new CancellationTokenSource(TimeSpan.FromSeconds(20)))
- {
- // Act
- await listener.StartAsync(source.Token);
- await publisher.StartAsync(source.Token);
+ using var source = new CancellationTokenSource(TimeSpan.FromSeconds(20));
+
+ // Act
+ await listener.StartAsync(source.Token);
+ await publisher.StartAsync(source.Token);
- var message = new TopicMessage();
+ var message = new TopicMessage();
- await publisher.PublishAsync(message, source.Token);
+ await publisher.PublishAsync(message, source.Token);
- var store = serviceProvider.GetService>();
+ var store = serviceProvider.GetService>();
- await Patiently.AssertThatAsync(OutputHelper,
- () => store.Messages.Any(msg => msg.Id == message.Id));
- }
+ await Patiently.AssertThatAsync(OutputHelper,
+ () => store.Messages.Any(msg => msg.Id == message.Id));
}
[AwsFact]
@@ -125,12 +117,11 @@ public async Task Can_Create_Messaging_Bus()
IMessagePublisher publisher = serviceProvider.GetRequiredService();
IMessagingBus listener = serviceProvider.GetRequiredService();
- using (var source = new CancellationTokenSource(TimeSpan.FromSeconds(20)))
- {
- // Act
- await listener.StartAsync(source.Token);
- await publisher.StartAsync(source.Token);
- }
+ using var source = new CancellationTokenSource(TimeSpan.FromSeconds(20));
+
+ // Act
+ await listener.StartAsync(source.Token);
+ await publisher.StartAsync(source.Token);
}
[AwsFact]
@@ -153,26 +144,25 @@ public async Task Can_Create_Messaging_Bus_With_Contributors()
IMessagePublisher publisher = serviceProvider.GetRequiredService();
IMessagingBus listener = serviceProvider.GetRequiredService();
- using (var source = new CancellationTokenSource(TimeSpan.FromSeconds(20)))
- {
- // Act
- await listener.StartAsync(source.Token);
- await publisher.StartAsync(source.Token);
+ using var source = new CancellationTokenSource(TimeSpan.FromSeconds(20));
+
+ // Act
+ await listener.StartAsync(source.Token);
+ await publisher.StartAsync(source.Token);
- var message = new QueueMessage();
+ var message = new QueueMessage();
- await publisher.PublishAsync(message, source.Token);
+ await publisher.PublishAsync(message, source.Token);
- // Assert
- var messageStore = serviceProvider.GetService>();
+ // Assert
+ var messageStore = serviceProvider.GetService>();
- await Patiently.AssertThatAsync(OutputHelper,
- () =>
- {
- messageStore.Messages.ShouldContain(msg =>
- msg.Id.Equals(message.Id));
- });
- }
+ await Patiently.AssertThatAsync(OutputHelper,
+ () =>
+ {
+ messageStore.Messages.ShouldContain(msg =>
+ msg.Id.Equals(message.Id));
+ });
}
private sealed class AwsContributor : IMessageBusConfigurationContributor
@@ -185,14 +175,9 @@ public void Configure(MessagingBusBuilder builder)
}
}
- private sealed class MessagingContributor : IMessageBusConfigurationContributor
+ private sealed class MessagingContributor(IServiceProvider serviceProvider) : IMessageBusConfigurationContributor
{
- public MessagingContributor(IServiceProvider serviceProvider)
- {
- ServiceProvider = serviceProvider;
- }
-
- private IServiceProvider ServiceProvider { get; }
+ private IServiceProvider ServiceProvider { get; } = serviceProvider;
public void Configure(MessagingBusBuilder builder)
{
@@ -259,4 +244,4 @@ public void ReceiveMessageTime(TimeSpan duration, string queueName, string regio
public void HandlerExecutionTime(Type handlerType, Type messageType, TimeSpan duration)
{ }
}
-}
\ No newline at end of file
+}
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Monitoring/WhenUsingAMessageMonitor.cs b/tests/JustSaying.IntegrationTests/Fluent/Monitoring/WhenUsingAMessageMonitor.cs
index 64a322123..1a6e22ba2 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Monitoring/WhenUsingAMessageMonitor.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Monitoring/WhenUsingAMessageMonitor.cs
@@ -8,11 +8,8 @@
namespace JustSaying.Fluent.Monitoring;
-public class WhenUsingAMessageMonitor : IntegrationTestBase
+public class WhenUsingAMessageMonitor(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenUsingAMessageMonitor(ITestOutputHelper outputHelper) : base(outputHelper)
- { }
-
[AwsFact]
public async Task MonitorShouldBeCalled()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToAQueue.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToAQueue.cs
index 5842d6952..650a9a3c0 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToAQueue.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToAQueue.cs
@@ -4,12 +4,8 @@
namespace JustSaying.IntegrationTests.Fluent.Publishing;
-public class WhenAMessageIsPublishedToAQueue : IntegrationTestBase
+public class WhenAMessageIsPublishedToAQueue(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenAMessageIsPublishedToAQueue(ITestOutputHelper outputHelper)
- : base(outputHelper)
- { }
-
[AwsFact]
public async Task Then_The_Message_Is_Handled()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToAQueueWithSystemTextJson.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToAQueueWithSystemTextJson.cs
index b374406fb..8c00e3d34 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToAQueueWithSystemTextJson.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToAQueueWithSystemTextJson.cs
@@ -5,13 +5,8 @@
namespace JustSaying.IntegrationTests.Fluent.Publishing;
-public class WhenAMessageIsPublishedToAQueueWithSystemTextJson : IntegrationTestBase
+public class WhenAMessageIsPublishedToAQueueWithSystemTextJson(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenAMessageIsPublishedToAQueueWithSystemTextJson(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_The_Message_Is_Handled()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATenantedTopic.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATenantedTopic.cs
index 55acd0b3b..a2fb59f3b 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATenantedTopic.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATenantedTopic.cs
@@ -7,13 +7,8 @@
namespace JustSaying.IntegrationTests.Fluent.Publishing;
-public class WhenAMessageIsPublishedToATenantedTopic
- : IntegrationTestBase
+public class WhenAMessageIsPublishedToATenantedTopic(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenAMessageIsPublishedToATenantedTopic(ITestOutputHelper outputHelper)
- : base(outputHelper)
- { }
-
[AwsFact]
public async Task Then_The_Message_Is_Handled()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopic.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopic.cs
index 76afb9f66..e6921da68 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopic.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopic.cs
@@ -4,13 +4,8 @@
namespace JustSaying.IntegrationTests.Fluent.Publishing;
-public class WhenAMessageIsPublishedToATopic : IntegrationTestBase
+public class WhenAMessageIsPublishedToATopic(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenAMessageIsPublishedToATopic(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_The_Message_Is_Handled()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopicWithACustomName.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopicWithACustomName.cs
index 54678b845..fb579cfcd 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopicWithACustomName.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopicWithACustomName.cs
@@ -5,12 +5,8 @@
namespace JustSaying.IntegrationTests.Fluent.Publishing;
-public class WhenAMessageIsPublishedToATopicWithACustomName : IntegrationTestBase
+public class WhenAMessageIsPublishedToATopicWithACustomName(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenAMessageIsPublishedToATopicWithACustomName(ITestOutputHelper outputHelper)
- : base(outputHelper)
- { }
-
[AwsFact]
public async Task Then_The_Message_Is_Handled()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopicWithSystemTextJson.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopicWithSystemTextJson.cs
index a006c897f..6e4e2aeb0 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopicWithSystemTextJson.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedToATopicWithSystemTextJson.cs
@@ -5,13 +5,8 @@
namespace JustSaying.IntegrationTests.Fluent.Publishing;
-public class WhenAMessageIsPublishedToATopicWithSystemTextJson : IntegrationTestBase
+public class WhenAMessageIsPublishedToATopicWithSystemTextJson(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenAMessageIsPublishedToATopicWithSystemTextJson(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_The_Message_Is_Handled()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedWithoutStartingThePublisher.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedWithoutStartingThePublisher.cs
index 976d50283..9f3f4f83a 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedWithoutStartingThePublisher.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenAMessageIsPublishedWithoutStartingThePublisher.cs
@@ -3,12 +3,8 @@
namespace JustSaying.IntegrationTests.Fluent.Publishing;
-public class WhenAMessageIsPublishedWithoutStartingThePublisher : IntegrationTestBase
+public class WhenAMessageIsPublishedWithoutStartingThePublisher(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenAMessageIsPublishedWithoutStartingThePublisher(ITestOutputHelper outputHelper) : base(
- outputHelper)
- { }
-
[AwsFact]
public async Task Then_The_PushlishShouldThrow()
{
@@ -33,4 +29,4 @@ await Assert.ThrowsAsync(
() => publisher.PublishAsync(message, cancellationToken));
});
}
-}
\ No newline at end of file
+}
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenCreatingAMessagePublisher.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenCreatingAMessagePublisher.cs
index 23cc72e52..9d7151191 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenCreatingAMessagePublisher.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenCreatingAMessagePublisher.cs
@@ -4,13 +4,8 @@
namespace JustSaying.IntegrationTests.Fluent.Publishing;
-public class WhenCreatingAMessagePublisher : IntegrationTestBase
+public class WhenCreatingAMessagePublisher(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenCreatingAMessagePublisher(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_The_Queues_Exist()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenInterrogatingTheBus.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenInterrogatingTheBus.cs
index 7447babc0..1a67993b0 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenInterrogatingTheBus.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenInterrogatingTheBus.cs
@@ -4,11 +4,8 @@
namespace JustSaying.IntegrationTests.Fluent.Publishing;
-public class WhenInterrogatingTheBus : IntegrationTestBase
+public class WhenInterrogatingTheBus(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenInterrogatingTheBus(ITestOutputHelper outputHelper) : base(outputHelper)
- { }
-
[AwsFact]
public async Task Then_The_Interrogation_Result_Should_Be_Returned()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenPublishingWithNoRegisteredMessages.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenPublishingWithNoRegisteredMessages.cs
index aaeb2b078..9efd68341 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenPublishingWithNoRegisteredMessages.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenPublishingWithNoRegisteredMessages.cs
@@ -4,13 +4,8 @@
namespace JustSaying.IntegrationTests.Fluent.Publishing;
-public class WhenPublishingWithNoRegisteredMessages : IntegrationTestBase
+public class WhenPublishingWithNoRegisteredMessages(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenPublishingWithNoRegisteredMessages(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_An_Exception_Is_Thrown()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenPublishingWithoutAMonitor.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenPublishingWithoutAMonitor.cs
index 4750fb7ab..fd85aaa1d 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenPublishingWithoutAMonitor.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenPublishingWithoutAMonitor.cs
@@ -7,13 +7,8 @@
namespace JustSaying.IntegrationTests.Fluent.Publishing;
-public class WhenPublishingWithoutAMonitor : IntegrationTestBase
+public class WhenPublishingWithoutAMonitor(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenPublishingWithoutAMonitor(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task A_Message_Can_Still_Be_Published_To_A_Queue()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenRegisteringAPublisherForRegion.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenRegisteringAPublisherForRegion.cs
index 6ae62c5fb..ea204a38f 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenRegisteringAPublisherForRegion.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenRegisteringAPublisherForRegion.cs
@@ -6,12 +6,8 @@
namespace JustSaying.IntegrationTests.Fluent.Publishing;
-public class WhenRegisteringAPublisherForRegion : IntegrationTestBase
+public class WhenRegisteringAPublisherForRegion(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenRegisteringAPublisherForRegion(ITestOutputHelper outputHelper)
- : base(outputHelper)
- { }
-
[AwsFact]
public async Task Then_A_Topic_Is_Created_In_That_Region()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenRegisteringAPublisherWithTags.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenRegisteringAPublisherWithTags.cs
index c2de04a13..a9b2768e5 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenRegisteringAPublisherWithTags.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenRegisteringAPublisherWithTags.cs
@@ -7,12 +7,8 @@
namespace JustSaying.IntegrationTests.Fluent.Publishing;
-public class WhenRegisteringAPublisherWithTags : IntegrationTestBase
+public class WhenRegisteringAPublisherWithTags(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenRegisteringAPublisherWithTags(ITestOutputHelper outputHelper)
- : base(outputHelper)
- { }
-
[NotSimulatorFact]
public async Task Then_A_Topic_Is_Created_With_The_Correct_Tags()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenTheErrorQueueDisabled.cs b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenTheErrorQueueDisabled.cs
index 910ee6cb0..d777ced30 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenTheErrorQueueDisabled.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Publishing/WhenTheErrorQueueDisabled.cs
@@ -4,13 +4,8 @@
namespace JustSaying.IntegrationTests.Fluent.Publishing;
-public class WhenTheErrorQueueDisabled : IntegrationTestBase
+public class WhenTheErrorQueueDisabled(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenTheErrorQueueDisabled(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_The_Error_Queue_Does_Not_Exist()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/HandlerWithMessageContext.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/HandlerWithMessageContext.cs
index 46dd97a28..4680a7ca3 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/HandlerWithMessageContext.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/HandlerWithMessageContext.cs
@@ -5,32 +5,19 @@
namespace JustSaying.IntegrationTests.Fluent.Subscribing;
-internal class HandlerWithMessageContext : IHandlerAsync
+internal class HandlerWithMessageContext(
+ IMessageContextReader messageContextReader,
+ Future future,
+ ILogger logger) : IHandlerAsync
{
- private readonly ILogger _logger;
- private readonly IMessageContextReader _messageContextReader;
+ private readonly ILogger _logger = logger;
+ private readonly IMessageContextReader _messageContextReader = messageContextReader;
- public HandlerWithMessageContext(
- IMessageContextReader messageContextReader,
- Future future,
- ILogger logger)
- {
- _messageContextReader = messageContextReader;
- Future = future;
- _logger = logger;
- }
-
- public Future Future { get; }
+ public Future Future { get; } = future;
public async Task Handle(SimpleMessage message)
{
- var messageContext = _messageContextReader.MessageContext;
-
- if (messageContext == null)
- {
- throw new InvalidOperationException("Message context was not found");
- }
-
+ var messageContext = _messageContextReader.MessageContext ?? throw new InvalidOperationException("Message context was not found");
_logger.LogInformation(
"Message context found with queue URI {QueueUri} and message body {MessageBody}.",
messageContext.QueueUri,
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/Newtonsoft/WhenHandlingAMessageWithBinaryAttributes.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/Newtonsoft/WhenHandlingAMessageWithBinaryAttributes.cs
index ff1947576..42bb3854a 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/Newtonsoft/WhenHandlingAMessageWithBinaryAttributes.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/Newtonsoft/WhenHandlingAMessageWithBinaryAttributes.cs
@@ -7,27 +7,19 @@
namespace JustSaying.Fluent.Subscribing.Newtonsoft;
-public class WhenHandlingAMessageWithBinaryAttributes : IntegrationTestBase
+public class WhenHandlingAMessageWithBinaryAttributes(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenHandlingAMessageWithBinaryAttributes(ITestOutputHelper outputHelper) : base(outputHelper)
- { }
-
- public class SimpleMessageWithBinaryAttributesHandler : IHandlerAsync
+ public class SimpleMessageWithBinaryAttributesHandler(IMessageContextAccessor contextAccessor) : IHandlerAsync
{
- private readonly IMessageContextAccessor _contextAccessor;
+ private readonly IMessageContextAccessor _contextAccessor = contextAccessor;
- public SimpleMessageWithBinaryAttributesHandler(IMessageContextAccessor contextAccessor)
- {
- _contextAccessor = contextAccessor;
- HandledMessages = new List<(MessageContext, SimpleMessage)>();
- }
public Task Handle(SimpleMessage message)
{
HandledMessages.Add((_contextAccessor.MessageContext, message));
return Task.FromResult(true);
}
- public List<(MessageContext context, SimpleMessage message)> HandledMessages { get; }
+ public List<(MessageContext context, SimpleMessage message)> HandledMessages { get; } = new List<(MessageContext, SimpleMessage)>();
}
[AwsFact]
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/Newtonsoft/WhenHandlingAMessageWithStringAttributes.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/Newtonsoft/WhenHandlingAMessageWithStringAttributes.cs
index 3eed19a2f..f7fc244f2 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/Newtonsoft/WhenHandlingAMessageWithStringAttributes.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/Newtonsoft/WhenHandlingAMessageWithStringAttributes.cs
@@ -6,27 +6,19 @@
namespace JustSaying.Fluent.Subscribing.Newtonsoft;
-public class WhenHandlingAMessageWithStringAttributes : IntegrationTestBase
+public class WhenHandlingAMessageWithStringAttributes(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenHandlingAMessageWithStringAttributes(ITestOutputHelper outputHelper) : base(outputHelper)
- { }
-
- public class SimpleMessageWithStringAttributesHandler : IHandlerAsync
+ public class SimpleMessageWithStringAttributesHandler(IMessageContextAccessor contextAccessor) : IHandlerAsync
{
- private readonly IMessageContextAccessor _contextAccessor;
+ private readonly IMessageContextAccessor _contextAccessor = contextAccessor;
- public SimpleMessageWithStringAttributesHandler(IMessageContextAccessor contextAccessor)
- {
- _contextAccessor = contextAccessor;
- HandledMessages = new List<(MessageContext, SimpleMessage)>();
- }
public Task Handle(SimpleMessage message)
{
HandledMessages.Add((_contextAccessor.MessageContext, message));
return Task.FromResult(true);
}
- public List<(MessageContext context, SimpleMessage message)> HandledMessages { get; }
+ public List<(MessageContext context, SimpleMessage message)> HandledMessages { get; } = new List<(MessageContext, SimpleMessage)>();
}
[AwsFact]
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/RecordingMessageContextAccessor.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/RecordingMessageContextAccessor.cs
index 585c0ccd7..17614e15e 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/RecordingMessageContextAccessor.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/RecordingMessageContextAccessor.cs
@@ -2,18 +2,13 @@
namespace JustSaying.IntegrationTests.Fluent.Subscribing;
-public class RecordingMessageContextAccessor : IMessageContextAccessor, IMessageContextReader
+public class RecordingMessageContextAccessor(IMessageContextAccessor inner) : IMessageContextAccessor, IMessageContextReader
{
- private readonly IMessageContextAccessor _inner;
- private readonly List _valuesWritten = new List();
+ private readonly IMessageContextAccessor _inner = inner;
+ private readonly List _valuesWritten = new();
public IReadOnlyCollection ValuesWritten => _valuesWritten;
- public RecordingMessageContextAccessor(IMessageContextAccessor inner)
- {
- _inner = inner;
- }
-
public MessageContext MessageContext
{
get => _inner.MessageContext;
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/SystemTextJson/WhenHandlingAMessageWithBinaryAttributes.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/SystemTextJson/WhenHandlingAMessageWithBinaryAttributes.cs
index a800e0d4a..79f41b583 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/SystemTextJson/WhenHandlingAMessageWithBinaryAttributes.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/SystemTextJson/WhenHandlingAMessageWithBinaryAttributes.cs
@@ -8,27 +8,19 @@
namespace JustSaying.Fluent.Subscribing.SystemTextJson;
-public class WhenHandlingAMessageWithBinaryAttributes : IntegrationTestBase
+public class WhenHandlingAMessageWithBinaryAttributes(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenHandlingAMessageWithBinaryAttributes(ITestOutputHelper outputHelper) : base(outputHelper)
- { }
-
- public class SimpleMessageWithBinaryAttributesHandler : IHandlerAsync
+ public class SimpleMessageWithBinaryAttributesHandler(IMessageContextAccessor contextAccessor) : IHandlerAsync
{
- private readonly IMessageContextAccessor _contextAccessor;
+ private readonly IMessageContextAccessor _contextAccessor = contextAccessor;
- public SimpleMessageWithBinaryAttributesHandler(IMessageContextAccessor contextAccessor)
- {
- _contextAccessor = contextAccessor;
- HandledMessages = new List<(MessageContext, SimpleMessage)>();
- }
public Task Handle(SimpleMessage message)
{
HandledMessages.Add((_contextAccessor.MessageContext, message));
return Task.FromResult(true);
}
- public List<(MessageContext context, SimpleMessage message)> HandledMessages { get; }
+ public List<(MessageContext context, SimpleMessage message)> HandledMessages { get; } = new List<(MessageContext, SimpleMessage)>();
}
[AwsFact]
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/SystemTextJson/WhenHandlingAMessageWithStringAttributes.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/SystemTextJson/WhenHandlingAMessageWithStringAttributes.cs
index 5a1eb9885..d03cc8762 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/SystemTextJson/WhenHandlingAMessageWithStringAttributes.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/SystemTextJson/WhenHandlingAMessageWithStringAttributes.cs
@@ -7,27 +7,19 @@
namespace JustSaying.Fluent.Subscribing.SystemTextJson;
-public class WhenHandlingAMessageWithStringAttributes : IntegrationTestBase
+public class WhenHandlingAMessageWithStringAttributes(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenHandlingAMessageWithStringAttributes(ITestOutputHelper outputHelper) : base(outputHelper)
- { }
-
- public class SimpleMessageWithStringAttributesHandler : IHandlerAsync
+ public class SimpleMessageWithStringAttributesHandler(IMessageContextAccessor contextAccessor) : IHandlerAsync
{
- private readonly IMessageContextAccessor _contextAccessor;
+ private readonly IMessageContextAccessor _contextAccessor = contextAccessor;
- public SimpleMessageWithStringAttributesHandler(IMessageContextAccessor contextAccessor)
- {
- _contextAccessor = contextAccessor;
- HandledMessages = new List<(MessageContext, SimpleMessage)>();
- }
public Task Handle(SimpleMessage message)
{
HandledMessages.Add((_contextAccessor.MessageContext, message));
return Task.FromResult(true);
}
- public List<(MessageContext context, SimpleMessage message)> HandledMessages { get; }
+ public List<(MessageContext context, SimpleMessage message)> HandledMessages { get; } = new List<(MessageContext, SimpleMessage)>();
}
[AwsFact]
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerThrowsAnExceptionWithAMonitor.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerThrowsAnExceptionWithAMonitor.cs
index 3cb9e2de2..b950e638f 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerThrowsAnExceptionWithAMonitor.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerThrowsAnExceptionWithAMonitor.cs
@@ -7,13 +7,8 @@
namespace JustSaying.IntegrationTests.Fluent.Subscribing;
-public class WhenAHandlerThrowsAnExceptionWithAMonitor : IntegrationTestBase
+public class WhenAHandlerThrowsAnExceptionWithAMonitor(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenAHandlerThrowsAnExceptionWithAMonitor(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_The_Message_Is_Handled()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerThrowsAnExceptionWithNoMonitor.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerThrowsAnExceptionWithNoMonitor.cs
index 48d8c29bf..1c730d4c1 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerThrowsAnExceptionWithNoMonitor.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerThrowsAnExceptionWithNoMonitor.cs
@@ -6,13 +6,8 @@
namespace JustSaying.IntegrationTests.Fluent.Subscribing;
-public class WhenAHandlerThrowsAnExceptionWithNoMonitor : IntegrationTestBase
+public class WhenAHandlerThrowsAnExceptionWithNoMonitor(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenAHandlerThrowsAnExceptionWithNoMonitor(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_The_Message_Is_Handled()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerUsesMessageContext.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerUsesMessageContext.cs
index 95cca5a07..2f18d3d65 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerUsesMessageContext.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenAHandlerUsesMessageContext.cs
@@ -5,13 +5,8 @@
namespace JustSaying.IntegrationTests.Fluent.Subscribing;
-public class WhenAHandlerUsesMessageContext : IntegrationTestBase
+public class WhenAHandlerUsesMessageContext(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenAHandlerUsesMessageContext(ITestOutputHelper outputHelper) :
- base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_The_Message_Is_Handled()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenApplyingDefaultMiddlewares.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenApplyingDefaultMiddlewares.cs
index 36e5a0328..b12c0efea 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenApplyingDefaultMiddlewares.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenApplyingDefaultMiddlewares.cs
@@ -5,11 +5,8 @@
namespace JustSaying.IntegrationTests.Fluent.Subscribing;
-public class WhenApplyingDefaultMiddlewares : IntegrationTestBase
+public class WhenApplyingDefaultMiddlewares(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenApplyingDefaultMiddlewares(ITestOutputHelper outputHelper) : base(outputHelper)
- { }
-
class OuterTestMiddleware : InspectableMiddleware
{ }
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenDefaultMiddlewaresAreNotApplied.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenDefaultMiddlewaresAreNotApplied.cs
index 08d6e3884..1d00f4a65 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenDefaultMiddlewaresAreNotApplied.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenDefaultMiddlewaresAreNotApplied.cs
@@ -5,11 +5,8 @@
namespace JustSaying.IntegrationTests.Fluent.Subscribing;
-public class WhenDefaultMiddlewaresAreNotApplied : IntegrationTestBase
+public class WhenDefaultMiddlewaresAreNotApplied(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenDefaultMiddlewaresAreNotApplied(ITestOutputHelper outputHelper) : base(outputHelper)
- { }
-
[AwsFact]
public async Task Then_The_Pipeline_Should_Only_Contain_User_Specified_Middlewares()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenHandlerIsDeclaredAsExactlyOnce.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenHandlerIsDeclaredAsExactlyOnce.cs
index 935e41a3c..46808b928 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenHandlerIsDeclaredAsExactlyOnce.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenHandlerIsDeclaredAsExactlyOnce.cs
@@ -6,13 +6,8 @@
namespace JustSaying.IntegrationTests.Fluent.Subscribing;
-public class WhenHandlerIsDeclaredAsExactlyOnce : IntegrationTestBase
+public class WhenHandlerIsDeclaredAsExactlyOnce(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenHandlerIsDeclaredAsExactlyOnce(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_The_Handler_Only_Receives_The_Message_Once()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenHandlingMultipleTopics.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenHandlingMultipleTopics.cs
index f2ca6e03f..5d3e07668 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenHandlingMultipleTopics.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenHandlingMultipleTopics.cs
@@ -10,13 +10,8 @@
namespace JustSaying.IntegrationTests.Fluent.Subscribing;
-public class WhenHandlingMultipleTopics : IntegrationTestBase
+public class WhenHandlingMultipleTopics(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenHandlingMultipleTopics(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[NotSimulatorFact]
public async Task Sqs_Policy_Is_Applied_With_Wildcard()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenReceivingIsThrottled.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenReceivingIsThrottled.cs
index d207e5009..2f49d461e 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenReceivingIsThrottled.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenReceivingIsThrottled.cs
@@ -11,13 +11,8 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing;
/// concurrency of 2, the long running handler will consume one slot, and every other message will be
/// processed in order in the other slot. The result should be exactly in-order delivery for this test.
///
-public sealed class WhenReceivingIsThrottled : IntegrationTestBase
+public sealed class WhenReceivingIsThrottled(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenReceivingIsThrottled(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_The_Messages_Are_Handled_With_Throttle()
{
@@ -78,40 +73,27 @@ await WhenAsync(
});
}
- private class WaitingMessage : Message, IComparable
+ private class WaitingMessage(int order, TimeSpan timeToWait) : Message, IComparable
{
- public WaitingMessage(int order, TimeSpan timeToWait)
- {
- Order = order;
- TimeToWait = timeToWait;
- }
-
- public TimeSpan TimeToWait { get; }
- public int Order { get; }
+ public TimeSpan TimeToWait { get; } = timeToWait;
+ public int Order { get; } = order;
public int CompareTo(WaitingMessage other)
{
if (ReferenceEquals(this, other)) return 0;
- if (ReferenceEquals(null, other)) return 1;
+ if (other is null) return 1;
return Order.CompareTo(other.Order);
}
}
- private class InspectableWaitingHandler : InspectableHandler
+ private class InspectableWaitingHandler(ITestOutputHelper outputHelper) : InspectableHandler
{
- private readonly ITestOutputHelper _output;
-
- public InspectableWaitingHandler(ITestOutputHelper testOutputHelper)
- {
- _output = testOutputHelper;
- }
-
public override async Task Handle(WaitingMessage message)
{
await base.Handle(message);
- _output.WriteLine($"Running task {message.Order} which will wait for {message.TimeToWait.TotalMilliseconds}ms");
+ outputHelper.WriteLine($"Running task {message.Order} which will wait for {message.TimeToWait.TotalMilliseconds}ms");
await Task.Delay(message.TimeToWait);
return true;
}
}
-}
\ No newline at end of file
+}
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASqsTopicSubscriber.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASqsTopicSubscriber.cs
index d8c2da7ac..c228c7fd7 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASqsTopicSubscriber.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASqsTopicSubscriber.cs
@@ -4,13 +4,8 @@
namespace JustSaying.IntegrationTests.Fluent.Subscribing;
-public class WhenRegisteringASqsTopicSubscriber : IntegrationTestBase
+public class WhenRegisteringASqsTopicSubscriber(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenRegisteringASqsTopicSubscriber(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_A_Queue_Is_Created()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASqsTopicSubscriberForRegion.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASqsTopicSubscriberForRegion.cs
index e61c8bc46..6cd60c2a8 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASqsTopicSubscriberForRegion.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASqsTopicSubscriberForRegion.cs
@@ -6,12 +6,8 @@
namespace JustSaying.IntegrationTests.Fluent.Subscribing;
-public class WhenRegisteringASqsTopicSubscriberForRegion : IntegrationTestBase
+public class WhenRegisteringASqsTopicSubscriberForRegion(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenRegisteringASqsTopicSubscriberForRegion(ITestOutputHelper outputHelper)
- : base(outputHelper)
- { }
-
[AwsFact]
public async Task Then_A_Queue_Is_Created()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASubscriberWithTags.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASubscriberWithTags.cs
index 4eeaf374b..0aad9b72f 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASubscriberWithTags.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringASubscriberWithTags.cs
@@ -8,14 +8,10 @@
namespace JustSaying.IntegrationTests.Fluent.Subscribing;
-public class WhenRegisteringASubscriberWithTags : IntegrationTestBase
+public class WhenRegisteringASubscriberWithTags(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
private const string QueueName = "simple-message-queue-with-tags";
- public WhenRegisteringASubscriberWithTags(ITestOutputHelper outputHelper) : base(outputHelper)
- {
- }
-
[NotSimulatorFact]
public async Task Then_A_Queue_For_Topic_Subscription_Is_Created_With_The_Correct_Tags()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringATopicForAGenericMessage.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringATopicForAGenericMessage.cs
index 39f2c437a..329788f5a 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringATopicForAGenericMessage.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringATopicForAGenericMessage.cs
@@ -3,13 +3,8 @@
namespace JustSaying.IntegrationTests.Fluent.Subscribing;
-public class WhenRegisteringATopicForAGenericMessage : IntegrationTestBase
+public class WhenRegisteringATopicForAGenericMessage(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenRegisteringATopicForAGenericMessage(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_The_Message_Is_Handled()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringLongNameMessageTypeTopicSubscriber.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringLongNameMessageTypeTopicSubscriber.cs
index e9343d660..b1e0c05c8 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringLongNameMessageTypeTopicSubscriber.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenRegisteringLongNameMessageTypeTopicSubscriber.cs
@@ -5,13 +5,8 @@
namespace JustSaying.IntegrationTests.Fluent.Subscribing;
-public class WhenRegisteringLongNameMessageTypeTopicSubscriber : IntegrationTestBase
+public class WhenRegisteringLongNameMessageTypeTopicSubscriber(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenRegisteringLongNameMessageTypeTopicSubscriber(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_A_Queue_Is_Created()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenSubscribingToMultipleTopics.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenSubscribingToMultipleTopics.cs
index a5f20d376..110ac2f17 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenSubscribingToMultipleTopics.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenSubscribingToMultipleTopics.cs
@@ -4,11 +4,8 @@
namespace JustSaying.IntegrationTests.Fluent.Subscribing;
-public class WhenSubscribingToMultipleTopics : IntegrationTestBase
+public class WhenSubscribingToMultipleTopics(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenSubscribingToMultipleTopics(ITestOutputHelper outputHelper) : base(outputHelper)
- { }
-
[AwsFact]
public async Task Then_Both_Handlers_Receive_Messages()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenTwoDifferentHandlersHandleAnExactlyOnceMessage.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenTwoDifferentHandlersHandleAnExactlyOnceMessage.cs
index 3b1f450cb..c18c27daa 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenTwoDifferentHandlersHandleAnExactlyOnceMessage.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenTwoDifferentHandlersHandleAnExactlyOnceMessage.cs
@@ -5,13 +5,8 @@
namespace JustSaying.IntegrationTests.Fluent.Subscribing;
-public class WhenTwoDifferentHandlersHandleAnExactlyOnceMessage : IntegrationTestBase
+public class WhenTwoDifferentHandlersHandleAnExactlyOnceMessage(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenTwoDifferentHandlersHandleAnExactlyOnceMessage(ITestOutputHelper outputHelper)
- : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task Then_Both_Handlers_Receive_The_Message()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenUsingMultipleMiddlewares.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenUsingMultipleMiddlewares.cs
index ea0ddf65e..224da29e9 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenUsingMultipleMiddlewares.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenUsingMultipleMiddlewares.cs
@@ -4,11 +4,8 @@
namespace JustSaying.IntegrationTests.Fluent.Subscribing;
-public class WhenUsingMultipleMiddlewares : IntegrationTestBase
+public class WhenUsingMultipleMiddlewares(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public WhenUsingMultipleMiddlewares(ITestOutputHelper outputHelper) : base(outputHelper)
- { }
-
[AwsFact]
public async Task Then_The_Middlewares_Are_Called()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenUsingResourceAddresses.cs b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenUsingResourceAddresses.cs
index c3649c70a..71000d989 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenUsingResourceAddresses.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/Subscribing/WhenUsingResourceAddresses.cs
@@ -6,12 +6,8 @@
namespace JustSaying.IntegrationTests.Fluent.Subscribing;
-public class AddressPubSub : IntegrationTestBase
+public class AddressPubSub(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public AddressPubSub(ITestOutputHelper outputHelper) : base(outputHelper)
- {
- }
-
[AwsFact]
public async Task SimplePubSubWorks()
{
diff --git a/tests/JustSaying.IntegrationTests/Fluent/TestHelpers/CapturingTestOutputHelper.cs b/tests/JustSaying.IntegrationTests/Fluent/TestHelpers/CapturingTestOutputHelper.cs
index d2e33023c..a209243b9 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/TestHelpers/CapturingTestOutputHelper.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/TestHelpers/CapturingTestOutputHelper.cs
@@ -2,28 +2,21 @@
namespace JustSaying.IntegrationTests.Fluent.Subscribing;
-public class CapturingTestOutputHelper : ITestOutputHelper
+public class CapturingTestOutputHelper(ITestOutputHelper inner) : ITestOutputHelper
{
- private readonly ITestOutputHelper _inner;
- private readonly StringBuilder _sb;
+ private readonly StringBuilder _sb = new();
public string Output => _sb.ToString();
- public CapturingTestOutputHelper(ITestOutputHelper inner)
- {
- _inner = inner;
- _sb = new StringBuilder();
- }
-
public void WriteLine(string message)
{
_sb.AppendLine(message);
- _inner.WriteLine(message);
+ inner.WriteLine(message);
}
public void WriteLine(string format, params object[] args)
{
_sb.AppendLine(string.Format(format, args));
- _inner.WriteLine(format, args);
+ inner.WriteLine(format, args);
}
-}
\ No newline at end of file
+}
diff --git a/tests/JustSaying.IntegrationTests/Fluent/TestHelpers/MessageLockStore.cs b/tests/JustSaying.IntegrationTests/Fluent/TestHelpers/MessageLockStore.cs
index 813226ee2..194b1ba38 100644
--- a/tests/JustSaying.IntegrationTests/Fluent/TestHelpers/MessageLockStore.cs
+++ b/tests/JustSaying.IntegrationTests/Fluent/TestHelpers/MessageLockStore.cs
@@ -5,7 +5,7 @@ namespace JustSaying.IntegrationTests.Fluent.Subscribing;
public sealed class MessageLockStore : IMessageLockAsync
{
- private readonly ConcurrentDictionary _store = new ConcurrentDictionary();
+ private readonly ConcurrentDictionary _store = new();
public Task TryAcquireLockAsync(string key, TimeSpan howLong)
{
diff --git a/tests/JustSaying.IntegrationTests/Logging/LogContextTests.cs b/tests/JustSaying.IntegrationTests/Logging/LogContextTests.cs
index 17582e269..75a56205c 100644
--- a/tests/JustSaying.IntegrationTests/Logging/LogContextTests.cs
+++ b/tests/JustSaying.IntegrationTests/Logging/LogContextTests.cs
@@ -8,13 +8,8 @@
namespace JustSaying.Logging;
-public class LogContextTests : IntegrationTestBase
+public class LogContextTests(ITestOutputHelper outputHelper) : IntegrationTestBase(outputHelper)
{
- public LogContextTests(ITestOutputHelper outputHelper) : base(outputHelper)
- {
- }
-
-
[AwsFact]
public async Task PublishToTopicLogsShouldHaveContext()
{
diff --git a/tests/JustSaying.IntegrationTests/TestHandlers/BlockingOrderProcessor.cs b/tests/JustSaying.IntegrationTests/TestHandlers/BlockingOrderProcessor.cs
index 4139ab49c..6c18b7a34 100644
--- a/tests/JustSaying.IntegrationTests/TestHandlers/BlockingOrderProcessor.cs
+++ b/tests/JustSaying.IntegrationTests/TestHandlers/BlockingOrderProcessor.cs
@@ -4,10 +4,6 @@ namespace JustSaying.IntegrationTests.TestHandlers;
public class BlockingOrderProcessor : IHandlerAsync
{
- public BlockingOrderProcessor()
- {
- }
-
public int ReceivedMessageCount { get; private set; }
public TaskCompletionSource