From e2055e9332355af273bf4d19d847f34cf3791a69 Mon Sep 17 00:00:00 2001 From: Paul Reardon Date: Thu, 2 Jan 2025 21:53:21 +0000 Subject: [PATCH 1/8] Refactor and remove interperter --- src/Paramore.Brighter/CommandProcessor.cs | 82 +++++++++++-------- src/Paramore.Brighter/IAmAPipelineBuilder.cs | 5 +- .../IAmAnAsyncPipelineBuilder.cs | 3 +- src/Paramore.Brighter/Interpreter.cs | 67 --------------- src/Paramore.Brighter/PipelineBuilder.cs | 44 ++++------ ..._A_Handler_Is_Part_Of_An_Async_Pipeline.cs | 10 ++- .../When_A_Handler_Is_Part_of_A_Pipeline.cs | 10 ++- .../When_Building_A_Handler_For_A_Command.cs | 10 ++- ...Building_A_Handler_For_An_Async_Command.cs | 10 ++- ...lding_A_Pipeline_Allow_ForiegnAttribues.cs | 10 ++- ...ing_A_Pipeline_Allow_Pre_And_Post_Tasks.cs | 10 ++- ..._Failures_Should_Be_ConfigurationErrors.cs | 11 ++- ..._Building_A_Pipeline_Preserve_The_Order.cs | 10 ++- ...n_Building_A_Pipeline_With_Global_Inbox.cs | 13 +-- ...With_Global_Inbox_And_NoInbox_Attribute.cs | 13 +-- ...obal_Inbox_And_NoInbox_Attribute_Async .cs | 13 +-- ...ipeline_With_Global_Inbox_And_Use_Inbox.cs | 13 +-- ...e_With_Global_Inbox_And_Use_Inbox_Async.cs | 14 ++-- ...ding_A_Pipeline_With_Global_Inbox_Async.cs | 12 +-- ...line_With_Global_Inbox_Override_Context.cs | 13 +-- ...A_Sync_Pipeline_That_Has_Async_Handlers.cs | 10 ++- ...n_Async_Pipeline_Allow_ForiegnAttribues.cs | 10 ++- ...Async_Pipeline_Allow_Pre_And_Post_Tasks.cs | 10 ++- ..._Failures_Should_Be_ConfigurationErrors.cs | 11 ++- ...ng_An_Async_Pipeline_Preserve_The_Order.cs | 10 ++- ...n_Async_Pipeline_That_Has_Sync_Handlers.cs | 10 ++- ..._Finding_A_Hander_That_Has_Dependencies.cs | 10 ++- .../When_Finding_A_Handler_For_A_Command.cs | 10 ++- ...cised_The_Pipeline_Cleanup_Its_Handlers.cs | 15 ++-- 29 files changed, 236 insertions(+), 233 deletions(-) delete mode 100644 src/Paramore.Brighter/Interpreter.cs diff --git a/src/Paramore.Brighter/CommandProcessor.cs b/src/Paramore.Brighter/CommandProcessor.cs index 2345970d02..363589e74f 100644 --- a/src/Paramore.Brighter/CommandProcessor.cs +++ b/src/Paramore.Brighter/CommandProcessor.cs @@ -236,16 +236,21 @@ public void Send(T command, RequestContext? requestContext = null) where T : if (_subscriberRegistry is null) throw new ArgumentException("A subscriberRegistry must be configured."); - using var builder = new PipelineBuilder(_subscriberRegistry, _handlerFactorySync, _inboxConfiguration); + var observers = _subscriberRegistry.Get(); + + var handlerCount = observers.Count(); + + using var builder = new PipelineBuilder(_handlerFactorySync, _inboxConfiguration); try { s_logger.LogInformation("Building send pipeline for command: {CommandType} {Id}", command.GetType(), command.Id); - var handlerChain = builder.Build(context); - - AssertValidSendPipeline(command, handlerChain.Count()); + + AssertValidSendPipeline(command, handlerCount); + + var handler = builder.Build(observers.First(), context); - handlerChain.First().Handle(command); + handler.Handle(command); } catch (Exception e) { @@ -283,17 +288,22 @@ public async Task SendAsync( if (_subscriberRegistry is null) throw new ArgumentException("A subscriberRegistry must be configured."); + + var observers = _subscriberRegistry.Get(); + + var handlerCount = observers.Count(); - using var builder = new PipelineBuilder(_subscriberRegistry, _handlerFactoryAsync, _inboxConfiguration); + using var builder = new PipelineBuilder(_handlerFactoryAsync, _inboxConfiguration); try { s_logger.LogInformation("Building send async pipeline for command: {CommandType} {Id}", command.GetType(), command.Id); - var handlerChain = builder.BuildAsync(context, continueOnCapturedContext); - - AssertValidSendPipeline(command, handlerChain.Count()); + + AssertValidSendPipeline(command, handlerCount); + + var handler = builder.BuildAsync(observers.First(), context, continueOnCapturedContext); - await handlerChain.First().HandleAsync(command, cancellationToken) + await handler.HandleAsync(command, cancellationToken) .ConfigureAwait(continueOnCapturedContext); } catch (Exception e) @@ -331,23 +341,28 @@ public void Publish(T @event, RequestContext? requestContext = null) where T if (_subscriberRegistry is null) throw new ArgumentException("A subscriberRegistry must be configured."); - using var builder = new PipelineBuilder(_subscriberRegistry, _handlerFactorySync, _inboxConfiguration); - s_logger.LogInformation("Building send pipeline for event: {EventType} {Id}", @event.GetType(), - @event.Id); - var handlerChain = builder.Build(context); - - var handlerCount = handlerChain.Count(); - + var observers = _subscriberRegistry.Get(); + + var handlerCount = observers.Count(); + s_logger.LogInformation("Found {HandlerCount} pipelines for event: {EventType} {Id}", handlerCount, @event.GetType(), @event.Id); var exceptions = new ConcurrentBag(); - Parallel.ForEach(handlerChain, (handleRequests) => + // Parallel.ForEach(handlerChain, (handleRequests) => + // { + foreach (Type observer in observers) { + s_logger.LogInformation("Building send pipeline for event: {EventType} {Id}", @event.GetType(), + @event.Id); + using var builder = new PipelineBuilder(_handlerFactorySync, _inboxConfiguration); + + var handleRequests = builder.Build(observer, context); try { var handlerName = handleRequests.Name.ToString(); - handlerSpans[handlerName] = _tracer?.CreateSpan(CommandProcessorSpanOperation.Publish, @event, span, options: _instrumentationOptions)!; + handlerSpans[handlerName] = _tracer?.CreateSpan(CommandProcessorSpanOperation.Publish, @event, + span, options: _instrumentationOptions)!; context.Span = handlerSpans[handlerName]; handleRequests.Handle(@event); context.Span = span; @@ -356,7 +371,8 @@ public void Publish(T @event, RequestContext? requestContext = null) where T { exceptions.Add(e); } - }); + } + // }); _tracer?.LinkSpans(handlerSpans); @@ -404,30 +420,32 @@ public async Task PublishAsync( if (_subscriberRegistry is null) throw new ArgumentException("A subscriberRegistry must be configured."); - using var builder = new PipelineBuilder(_subscriberRegistry, _handlerFactoryAsync, _inboxConfiguration); + var observers = _subscriberRegistry.Get(); + + var handlerCount = observers.Count(); + + s_logger.LogInformation("Found {0} async pipelines for event: {EventType} {Id}", handlerCount, + @event.GetType(), @event.Id); + var handlerSpans = new ConcurrentDictionary(); try { s_logger.LogInformation("Building send async pipeline for event: {EventType} {Id}", @event.GetType(), @event.Id); - var handlerChain = builder.BuildAsync(context, continueOnCapturedContext); - var handlerCount = handlerChain.Count(); - - s_logger.LogInformation("Found {0} async pipelines for event: {EventType} {Id}", handlerCount, - @event.GetType(), @event.Id - ); - var exceptions = new ConcurrentBag(); try { var tasks = new List(); - foreach (var handleRequests in handlerChain) + foreach (var observer in observers) { - handlerSpans[handleRequests.Name.ToString()] = _tracer?.CreateSpan(CommandProcessorSpanOperation.Publish, @event, span, options: _instrumentationOptions)!; - context.Span =handlerSpans[handleRequests.Name.ToString()]; - tasks.Add(handleRequests.HandleAsync(@event, cancellationToken)); + using var builder = new PipelineBuilder(_handlerFactoryAsync, _inboxConfiguration); + var handler = builder.BuildAsync(observer, context, continueOnCapturedContext); + + handlerSpans[handler.Name.ToString()] = _tracer?.CreateSpan(CommandProcessorSpanOperation.Publish, @event, span, options: _instrumentationOptions)!; + context.Span =handlerSpans[handler.Name.ToString()]; + tasks.Add(handler.HandleAsync(@event, cancellationToken)); context.Span = span; } diff --git a/src/Paramore.Brighter/IAmAPipelineBuilder.cs b/src/Paramore.Brighter/IAmAPipelineBuilder.cs index 97f68f9e91..846d90c4ce 100644 --- a/src/Paramore.Brighter/IAmAPipelineBuilder.cs +++ b/src/Paramore.Brighter/IAmAPipelineBuilder.cs @@ -38,8 +38,9 @@ internal interface IAmAPipelineBuilder : IDisposable where TRequest : /// /// Builds the specified request context. /// + /// The handler type to build /// The request context. /// Pipelines<TRequest>. - Pipelines Build(IRequestContext requestContext); + IHandleRequests Build(Type type, IRequestContext requestContext); } -} \ No newline at end of file +} diff --git a/src/Paramore.Brighter/IAmAnAsyncPipelineBuilder.cs b/src/Paramore.Brighter/IAmAnAsyncPipelineBuilder.cs index e4a4e8e2da..3bb9344f19 100644 --- a/src/Paramore.Brighter/IAmAnAsyncPipelineBuilder.cs +++ b/src/Paramore.Brighter/IAmAnAsyncPipelineBuilder.cs @@ -39,9 +39,10 @@ internal interface IAmAnAsyncPipelineBuilder : IDisposable where TRequ /// /// Builds the specified request context. /// + /// The Handler Type /// The request context. /// Should we use the calling thread's synchronization context when continuing or a default thread synchronization context. Defaults to false /// - AsyncPipelines BuildAsync(IRequestContext requestContext, bool continueOnCapturedContext); + IHandleRequestsAsync BuildAsync(Type type, IRequestContext requestContext, bool continueOnCapturedContext); } } diff --git a/src/Paramore.Brighter/Interpreter.cs b/src/Paramore.Brighter/Interpreter.cs deleted file mode 100644 index 0766385bde..0000000000 --- a/src/Paramore.Brighter/Interpreter.cs +++ /dev/null @@ -1,67 +0,0 @@ -#region Licence -/* The MIT License (MIT) -Copyright © 2014 Ian Cooper - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. */ - -#endregion - -using System.Collections.Generic; -using System.Linq; - -namespace Paramore.Brighter -{ - internal class Interpreter where TRequest : class, IRequest - { - private readonly IAmASubscriberRegistry _registry; - private readonly IAmAHandlerFactorySync? _handlerFactorySync; - private readonly IAmAHandlerFactoryAsync? _asyncHandlerFactory; - - internal Interpreter(IAmASubscriberRegistry registry, IAmAHandlerFactorySync handlerFactorySync) - : this(registry, handlerFactorySync, null) - { } - - internal Interpreter(IAmASubscriberRegistry registry, IAmAHandlerFactoryAsync asyncHandlerFactory) - : this(registry, null, asyncHandlerFactory) - { } - - internal Interpreter(IAmASubscriberRegistry registry, IAmAHandlerFactorySync? handlerFactorySync, IAmAHandlerFactoryAsync? asyncHandlerFactory) - { - _registry = registry; - _handlerFactorySync = handlerFactorySync; - _asyncHandlerFactory = asyncHandlerFactory; - } - - internal IEnumerable> GetHandlers() - { - return new RequestHandlers( - _registry.Get() - .Select(handlerType => _handlerFactorySync!.Create(handlerType)) - .Cast>()); - } - - internal IEnumerable> GetAsyncHandlers() - { - return new AsyncRequestHandlers( - _registry.Get() - .Select(handlerType => _asyncHandlerFactory!.Create(handlerType)) - .Cast>()); - } - } -} diff --git a/src/Paramore.Brighter/PipelineBuilder.cs b/src/Paramore.Brighter/PipelineBuilder.cs index e270b79e4b..cb4f0153a3 100644 --- a/src/Paramore.Brighter/PipelineBuilder.cs +++ b/src/Paramore.Brighter/PipelineBuilder.cs @@ -41,7 +41,6 @@ public class PipelineBuilder : IAmAPipelineBuilder, IAmAnAsy private readonly IAmAHandlerFactorySync? _handlerFactorySync; private readonly InboxConfiguration? _inboxConfiguration; - private readonly Interpreter _interpreter; private readonly IAmALifetime _instanceScope; private readonly IAmAHandlerFactoryAsync? _asyncHandlerFactory; //GLOBAL! cache of handler attributes - won't change post-startup so avoid re-calculation. Method to clear cache below (if a broken test brought you here) @@ -52,46 +51,39 @@ public class PipelineBuilder : IAmAPipelineBuilder, IAmAnAsy /// Used to build a pipeline of handlers from the target handler and the attributes on that /// target handler which represent other filter steps in the pipeline /// - /// What handler services this request /// Callback to the user code to create instances of handlers /// Do we have a global attribute to add an inbox public PipelineBuilder( - IAmASubscriberRegistry registry, IAmAHandlerFactorySync handlerFactorySync, InboxConfiguration? inboxConfiguration = null) { _handlerFactorySync = handlerFactorySync; _inboxConfiguration = inboxConfiguration; _instanceScope = new HandlerLifetimeScope(handlerFactorySync); - _interpreter = new Interpreter(registry, handlerFactorySync); } public PipelineBuilder( - IAmASubscriberRegistry registry, IAmAHandlerFactoryAsync asyncHandlerFactory, InboxConfiguration? inboxConfiguration = null) { _asyncHandlerFactory = asyncHandlerFactory; _inboxConfiguration = inboxConfiguration; _instanceScope = new HandlerLifetimeScope(asyncHandlerFactory); - _interpreter = new Interpreter(registry, asyncHandlerFactory); } - public Pipelines Build(IRequestContext requestContext) + public IHandleRequests Build(Type type, IRequestContext requestContext) { + if(_handlerFactorySync is null) + throw new NullReferenceException("HandlerFactorySync is null"); + try { - var handlers = _interpreter.GetHandlers(); - - var pipelines = new Pipelines(); - - handlers.Each(handler => pipelines.Add(BuildPipeline(handler, requestContext))); - - pipelines.Each(handler => handler.AddToLifetime(_instanceScope)); - - return pipelines; + var handler = (RequestHandler)_handlerFactorySync.Create(type); + var pipeline = BuildPipeline(handler, requestContext); + pipeline.AddToLifetime(_instanceScope); + return pipeline; } - catch (Exception e) when (!(e is ConfigurationException)) + catch (Exception e) when (e is not ConfigurationException) { throw new ConfigurationException("Error when building pipeline, see inner Exception for details", e); } @@ -155,18 +147,18 @@ private IHandleRequests BuildPipeline(RequestHandler implici } - public AsyncPipelines BuildAsync(IRequestContext requestContext, bool continueOnCapturedContext) + public IHandleRequestsAsync BuildAsync(Type type, IRequestContext requestContext, bool continueOnCapturedContext) { + if(_asyncHandlerFactory is null) + throw new NullReferenceException("AsyncHandlerFactory is null"); + try { - var handlers = _interpreter.GetAsyncHandlers(); - - var pipelines = new AsyncPipelines(); - handlers.Each(handler => pipelines.Add(BuildAsyncPipeline(handler, requestContext, continueOnCapturedContext))); - - pipelines.Each(handler => handler.AddToLifetime(_instanceScope)); - - return pipelines; + var handler = (RequestHandlerAsync)_asyncHandlerFactory.Create(type); + var pipeline = BuildAsyncPipeline(handler, requestContext, continueOnCapturedContext); + pipeline.AddToLifetime(_instanceScope); + + return pipeline; } catch (Exception e) when(!(e is ConfigurationException)) { diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_Of_An_Async_Pipeline.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_Of_An_Async_Pipeline.cs index ec1ad03df4..44c49e4e12 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_Of_An_Async_Pipeline.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_Of_An_Async_Pipeline.cs @@ -37,11 +37,12 @@ public class PipelineBuilderAsyncTests : IDisposable { private readonly PipelineBuilder _pipelineBuilder; private IHandleRequestsAsync _pipeline; + private SubscriberRegistry _subscriberRegistry; public PipelineBuilderAsyncTests() { - var registry = new SubscriberRegistry(); - registry.RegisterAsync(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.RegisterAsync(); var container = new ServiceCollection(); container.AddTransient(); @@ -50,7 +51,7 @@ public PipelineBuilderAsyncTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory); + _pipelineBuilder = new PipelineBuilder((IAmAHandlerFactoryAsync)handlerFactory); PipelineBuilder.ClearPipelineCache(); } @@ -58,7 +59,8 @@ public PipelineBuilderAsyncTests() [Fact] public void When_A_Handler_Is_Part_Of_An_Async_Pipeline() { - _pipeline = _pipelineBuilder.BuildAsync(new RequestContext(), false).First(); + var observers = _subscriberRegistry.Get(); + _pipeline = _pipelineBuilder.BuildAsync(observers.First(), new RequestContext(), false); TracePipeline().ToString().Should().Contain("MyImplicitHandlerAsync"); TracePipeline().ToString().Should().Contain("MyLoggingHandlerAsync"); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_of_A_Pipeline.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_of_A_Pipeline.cs index 4e1144f738..54bed1d637 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_of_A_Pipeline.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_of_A_Pipeline.cs @@ -37,11 +37,12 @@ public class PipelineBuilderTests : IDisposable { private readonly PipelineBuilder _pipelineBuilder; private IHandleRequests _pipeline; + private SubscriberRegistry _subscriberRegistry; public PipelineBuilderTests() { - var registry = new SubscriberRegistry(); - registry.Register(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.Register(); var container = new ServiceCollection(); container.AddTransient(); @@ -50,14 +51,15 @@ public PipelineBuilderTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory); + _pipelineBuilder = new PipelineBuilder((IAmAHandlerFactorySync)handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_A_Handler_Is_Part_of_A_Pipeline() { - _pipeline = _pipelineBuilder.Build(new RequestContext()).First(); + var observers = _subscriberRegistry.Get(); + _pipeline = _pipelineBuilder.Build(observers.First(), new RequestContext()); TracePipeline().ToString().Should().Contain("MyImplicitHandler"); TracePipeline().ToString().Should().Contain("MyLoggingHandler"); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Handler_For_A_Command.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Handler_For_A_Command.cs index 0430fb99b3..2d12fe6ced 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Handler_For_A_Command.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Handler_For_A_Command.cs @@ -36,22 +36,24 @@ public class PipelineForCommandTests : IDisposable private readonly PipelineBuilder _chainBuilder; private IHandleRequests _chainOfResponsibility; private readonly RequestContext _requestContext; + private SubscriberRegistry _subscriberRegistry; public PipelineForCommandTests() { - var registry = new SubscriberRegistry(); - registry.Register(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.Register(); var handlerFactory = new SimpleHandlerFactorySync(_ => new MyCommandHandler()); _requestContext = new RequestContext(); - _chainBuilder = new PipelineBuilder(registry, handlerFactory); + _chainBuilder = new PipelineBuilder(handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_Building_A_Handler_For_A_Command() { - _chainOfResponsibility = _chainBuilder.Build(_requestContext).First(); + var observers = _subscriberRegistry.Get(); + _chainOfResponsibility = _chainBuilder.Build(observers.First(), _requestContext); _chainOfResponsibility.Context.Should().NotBeNull(); _chainOfResponsibility.Context.Should().BeSameAs(_requestContext); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Handler_For_An_Async_Command.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Handler_For_An_Async_Command.cs index 668d3c646f..4a04a92d4f 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Handler_For_An_Async_Command.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Handler_For_An_Async_Command.cs @@ -38,21 +38,23 @@ public class PipelineForCommandAsyncTests : IDisposable private static IHandleRequestsAsync _chainOfResponsibility; private static RequestContext _requestContext; private readonly IDictionary _receivedMessages = new Dictionary(); + private SubscriberRegistry _subscriberRegistry; public PipelineForCommandAsyncTests() { - var registry = new SubscriberRegistry(); - registry.RegisterAsync(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.RegisterAsync(); var handlerFactory = new SimpleHandlerFactoryAsync(_ => new MyCommandHandlerAsync(_receivedMessages)); _requestContext = new RequestContext(); - _chainBuilder = new PipelineBuilder(registry, asyncHandlerFactory: handlerFactory); + _chainBuilder = new PipelineBuilder(asyncHandlerFactory: handlerFactory); } [Fact] public void When_Building_A_Handler_For_An_Async_Command() { - _chainOfResponsibility = _chainBuilder.BuildAsync(_requestContext, false).First(); + var observers = _subscriberRegistry.Get(); + _chainOfResponsibility = _chainBuilder.BuildAsync(observers.First(), _requestContext, false); _chainOfResponsibility.Context.Should().NotBeNull(); _chainOfResponsibility.Context.Should().BeSameAs(_requestContext); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_ForiegnAttribues.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_ForiegnAttribues.cs index 73e592004c..d829b45f46 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_ForiegnAttribues.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_ForiegnAttribues.cs @@ -37,11 +37,12 @@ public class PipelineForeignAttributesTests : IDisposable { private readonly PipelineBuilder _pipelineBuilder; private IHandleRequests _pipeline; + private SubscriberRegistry _subscriberRegistry; public PipelineForeignAttributesTests() { - var registry = new SubscriberRegistry(); - registry.Register(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.Register(); var container = new ServiceCollection(); container.AddTransient(); @@ -51,14 +52,15 @@ public PipelineForeignAttributesTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory); + _pipelineBuilder = new PipelineBuilder((IAmAHandlerFactorySync)handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_Building_A_Pipeline_Allow_ForeignAttributes() { - _pipeline = _pipelineBuilder.Build(new RequestContext()).First(); + var observers = _subscriberRegistry.Get(); + _pipeline = _pipelineBuilder.Build(observers.First(), new RequestContext()); TraceFilters().ToString().Should().Be("MyValidationHandler`1|MyObsoleteCommandHandler|MyLoggingHandler`1|"); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_Pre_And_Post_Tasks.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_Pre_And_Post_Tasks.cs index bbe79cf7bc..5c7fa1bd64 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_Pre_And_Post_Tasks.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_Pre_And_Post_Tasks.cs @@ -38,11 +38,12 @@ public class PipelinePreAndPostFiltersTests : IDisposable { private readonly PipelineBuilder _pipelineBuilder; private IHandleRequests _pipeline; + private SubscriberRegistry _subscriberRegistry; public PipelinePreAndPostFiltersTests() { - var registry = new SubscriberRegistry(); - registry.Register(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.Register(); var container = new ServiceCollection(); container.AddTransient(); @@ -52,14 +53,15 @@ public PipelinePreAndPostFiltersTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory); + _pipelineBuilder = new PipelineBuilder((IAmAHandlerFactorySync)handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_Building_A_Pipeline_Allow_Pre_And_Post_Tasks() { - _pipeline = _pipelineBuilder.Build(new RequestContext()).First(); + var observers = _subscriberRegistry.Get(); + _pipeline = _pipelineBuilder.Build(observers.First(), new RequestContext()); TraceFilters().ToString().Should().Be("MyValidationHandler`1|MyPreAndPostDecoratedHandler|MyLoggingHandler`1|"); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Failures_Should_Be_ConfigurationErrors.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Failures_Should_Be_ConfigurationErrors.cs index a1e261736a..e1dc37f7de 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Failures_Should_Be_ConfigurationErrors.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Failures_Should_Be_ConfigurationErrors.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using FluentAssertions; using Paramore.Brighter.Core.Tests.CommandProcessors.TestDoubles; using Paramore.Brighter.Core.Tests.TestHelpers; @@ -10,24 +11,26 @@ public class BuildPipelineFaults { private readonly PipelineBuilder _chainBuilder; private readonly RequestContext _requestContext; + private SubscriberRegistry _subscriberRegistry; public BuildPipelineFaults() { - var registry = new SubscriberRegistry(); - registry.Register(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.Register(); //We'll simulate an IoC error var handlerFactory = new SimpleHandlerFactorySync(_ => throw new InvalidOperationException("Could no create handler")); _requestContext = new RequestContext(); - _chainBuilder = new PipelineBuilder(registry, handlerFactory); + _chainBuilder = new PipelineBuilder(handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_Building_A_Pipeline_Failures_Should_Be_ConfigurationErrors() { - var exception = Catch.Exception(() => _chainBuilder.Build(_requestContext)); + var observers = _subscriberRegistry.Get(); + var exception = Catch.Exception(() => _chainBuilder.Build(observers.First(), _requestContext)); exception.Should().NotBeNull(); exception.Should().BeOfType(); exception.InnerException.Should().BeOfType(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Preserve_The_Order.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Preserve_The_Order.cs index 924e307ea6..39286aa736 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Preserve_The_Order.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Preserve_The_Order.cs @@ -37,11 +37,12 @@ public class PipelineOrderingTests : IDisposable { private readonly PipelineBuilder _pipelineBuilder; private IHandleRequests _pipeline; + private SubscriberRegistry _subscriberRegistry; public PipelineOrderingTests() { - var registry = new SubscriberRegistry(); - registry.Register(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.Register(); var container = new ServiceCollection(); container.AddTransient(); @@ -51,13 +52,14 @@ public PipelineOrderingTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory); + _pipelineBuilder = new PipelineBuilder((IAmAHandlerFactorySync)handlerFactory); } [Fact] public void When_Building_A_Pipeline_Preserve_The_Order() { - _pipeline = _pipelineBuilder.Build(new RequestContext()).First(); + var observers = _subscriberRegistry.Get(); + _pipeline = _pipelineBuilder.Build(observers.First(), new RequestContext()); PipelineTracer().ToString().Should().Be("MyLoggingHandler`1|MyValidationHandler`1|MyDoubleDecoratedHandler|"); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox.cs index bc9787794a..3928856cfb 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; @@ -14,15 +15,16 @@ namespace Paramore.Brighter.Core.Tests.CommandProcessors.Pipeline public class PipelineGlobalInboxTests : IDisposable { private readonly PipelineBuilder _chainBuilder; - private Pipelines _chainOfResponsibility; + private IEnumerable> _chainOfResponsibility; private readonly RequestContext _requestContext; + private SubscriberRegistry _subscriberRegistry; public PipelineGlobalInboxTests() { IAmAnInboxSync inbox = new InMemoryInbox(new FakeTimeProvider()); - var registry = new SubscriberRegistry(); - registry.Register(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.Register(); var container = new ServiceCollection(); container.AddTransient(); @@ -36,7 +38,7 @@ public PipelineGlobalInboxTests() InboxConfiguration inboxConfiguration = new(); - _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder((IAmAHandlerFactorySync)handlerFactory, inboxConfiguration); PipelineBuilder.ClearPipelineCache(); } @@ -44,7 +46,8 @@ public PipelineGlobalInboxTests() public void When_Building_A_Pipeline_With_Global_inbox() { //act - _chainOfResponsibility = _chainBuilder.Build(_requestContext); + var observers = _subscriberRegistry.Get(); + _chainOfResponsibility = observers.Select(o => _chainBuilder.Build(o, _requestContext)); //assert var tracer = TracePipeline(_chainOfResponsibility.First()); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute.cs index 567e343719..1d7d9de9f9 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; @@ -13,16 +14,17 @@ namespace Paramore.Brighter.Core.Tests.CommandProcessors.Pipeline public class PipelineGlobalInboxNoInboxAttributeTests : IDisposable { private readonly PipelineBuilder _chainBuilder; - private Pipelines _chainOfResponsibility; + private IEnumerable> _chainOfResponsibility; private readonly RequestContext _requestContext; + private SubscriberRegistry _subscriberRegistry; public PipelineGlobalInboxNoInboxAttributeTests() { IAmAnInboxSync inbox = new InMemoryInbox(new FakeTimeProvider()); - var registry = new SubscriberRegistry(); - registry.Register(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.Register(); var container = new ServiceCollection(); container.AddTransient(); @@ -35,7 +37,7 @@ public PipelineGlobalInboxNoInboxAttributeTests() InboxConfiguration inboxConfiguration = new(); - _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder((IAmAHandlerFactorySync)handlerFactory, inboxConfiguration); } @@ -43,7 +45,8 @@ public PipelineGlobalInboxNoInboxAttributeTests() public void When_Building_A_Pipeline_With_Global_Inbox() { //act - _chainOfResponsibility = _chainBuilder.Build(_requestContext); + var observers = _subscriberRegistry.Get(); + _chainOfResponsibility = observers.Select(o => _chainBuilder.Build(o, _requestContext)); //assert var tracer = TracePipeline(_chainOfResponsibility.First()); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute_Async .cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute_Async .cs index 761ee42082..08294af9bf 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute_Async .cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute_Async .cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; @@ -13,16 +14,17 @@ namespace Paramore.Brighter.Core.Tests.CommandProcessors.Pipeline public class PipelineGlobalInboxNoInboxAttributeAsyncTests : IDisposable { private readonly PipelineBuilder _chainBuilder; - private AsyncPipelines _chainOfResponsibility; + private IEnumerable> _chainOfResponsibility; private readonly RequestContext _requestContext; + private SubscriberRegistry _subscriberRegistry; public PipelineGlobalInboxNoInboxAttributeAsyncTests() { IAmAnInboxSync inbox = new InMemoryInbox(new FakeTimeProvider()); - var registry = new SubscriberRegistry(); - registry.RegisterAsync(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.RegisterAsync(); var container = new ServiceCollection(); container.AddTransient(); @@ -35,7 +37,7 @@ public PipelineGlobalInboxNoInboxAttributeAsyncTests() InboxConfiguration inboxConfiguration = new(); - _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder((IAmAHandlerFactoryAsync)handlerFactory, inboxConfiguration); } @@ -43,7 +45,8 @@ public PipelineGlobalInboxNoInboxAttributeAsyncTests() public void When_Building_A_Pipeline_With_Global_Inbox_Async() { //act - _chainOfResponsibility = _chainBuilder.BuildAsync(_requestContext, false); + var observers = _subscriberRegistry.Get(); + _chainOfResponsibility = observers.Select(o => _chainBuilder.BuildAsync(o, _requestContext, false)); //assert var tracer = TracePipelineAsync(_chainOfResponsibility.First()); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox.cs index c2cab952a0..eafd20afa2 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; @@ -16,16 +17,17 @@ namespace Paramore.Brighter.Core.Tests.CommandProcessors.Pipeline public class PipelineGlobalInboxWhenUseInboxTests : IDisposable { private readonly PipelineBuilder _chainBuilder; - private Pipelines _chainOfResponsibility; + private IEnumerable> _chainOfResponsibility; private readonly RequestContext _requestContext; + private SubscriberRegistry _subscriberRegistry; public PipelineGlobalInboxWhenUseInboxTests() { IAmAnInboxSync inbox = new InMemoryInbox(new FakeTimeProvider()); - var registry = new SubscriberRegistry(); - registry.Register(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.Register(); var container = new ServiceCollection(); container.AddTransient(); @@ -43,7 +45,7 @@ public PipelineGlobalInboxWhenUseInboxTests() onceOnly: true, actionOnExists: OnceOnlyAction.Throw); - _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder((IAmAHandlerFactorySync)handlerFactory, inboxConfiguration); } @@ -58,7 +60,8 @@ public void When_Building_A_Pipeline_With_Global_Inbox() //act - _chainOfResponsibility = _chainBuilder.Build(_requestContext); + var observers = _subscriberRegistry.Get(); + _chainOfResponsibility = observers.Select(o => _chainBuilder.Build(o, _requestContext)); var chain = _chainOfResponsibility.First(); var myCommand = new MyCommand(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox_Async.cs index 790147ee5a..d5c1aaef47 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox_Async.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FluentAssertions; @@ -17,16 +18,16 @@ namespace Paramore.Brighter.Core.Tests.CommandProcessors.Pipeline public class PipelineGlobalInboxWhenUseInboxAsyncTests : IDisposable { private readonly PipelineBuilder _chainBuilder; - private AsyncPipelines _chainOfResponsibility; + private IEnumerable> _chainOfResponsibility; private readonly RequestContext _requestContext; - + private SubscriberRegistry _subscriberRegistry; public PipelineGlobalInboxWhenUseInboxAsyncTests() { IAmAnInboxSync inbox = new InMemoryInbox(new FakeTimeProvider()); - var registry = new SubscriberRegistry(); - registry.RegisterAsync(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.RegisterAsync(); var container = new ServiceCollection(); container.AddTransient(); @@ -45,7 +46,7 @@ public PipelineGlobalInboxWhenUseInboxAsyncTests() onceOnly: true, actionOnExists: OnceOnlyAction.Throw); - _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder((IAmAHandlerFactoryAsync)handlerFactory, inboxConfiguration); } @@ -60,7 +61,8 @@ public async Task When_Building_A_Pipeline_With_Global_Inbox() //act - _chainOfResponsibility = _chainBuilder.BuildAsync(_requestContext, false); + var observers = _subscriberRegistry.Get(); + _chainOfResponsibility = observers.Select(o => _chainBuilder.BuildAsync(o, _requestContext, false)); var chain = _chainOfResponsibility.First(); var myCommand = new MyCommand(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Async.cs index b6773892e3..58baa3a534 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Async.cs @@ -19,8 +19,9 @@ namespace Paramore.Brighter.Core.Tests.CommandProcessors.Pipeline public class PipelineGlobalInboxTestsAsync : IDisposable { private readonly PipelineBuilder _chainBuilder; - private AsyncPipelines _chainOfResponsibility; + private IEnumerable> _chainOfResponsibility; private readonly RequestContext _requestContext; + private SubscriberRegistry _subscriberRegistry; public PipelineGlobalInboxTestsAsync() @@ -28,8 +29,8 @@ public PipelineGlobalInboxTestsAsync() IAmAnInboxAsync inbox = new InMemoryInbox(new FakeTimeProvider()); var handler = new MyCommandHandlerAsync(new Dictionary()); - var registry = new SubscriberRegistry(); - registry.RegisterAsync(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.RegisterAsync(); var container = new ServiceCollection(); container.AddSingleton(handler); @@ -44,7 +45,7 @@ public PipelineGlobalInboxTestsAsync() InboxConfiguration inboxConfiguration = new(); - _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder((IAmAHandlerFactoryAsync)handlerFactory, inboxConfiguration); } @@ -52,7 +53,8 @@ public PipelineGlobalInboxTestsAsync() public void When_Building_A_Pipeline_With_Global_Inbox() { //act - _chainOfResponsibility = _chainBuilder.BuildAsync(_requestContext, false); + var observers = _subscriberRegistry.Get(); + _chainOfResponsibility = observers.Select(o => _chainBuilder.BuildAsync(o, _requestContext, false)); //assert var tracer = TracePipeline(_chainOfResponsibility.First()); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Override_Context.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Override_Context.cs index 85d869887c..44ac076d37 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Override_Context.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Override_Context.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; @@ -15,17 +16,18 @@ public class PipelineGlobalInboxContextTests : IDisposable { private const string CONTEXT_KEY = "TestHandlerNameOverride"; private readonly PipelineBuilder _chainBuilder; - private Pipelines _chainOfResponsibility; + private IEnumerable> _chainOfResponsibility; private readonly RequestContext _requestContext; private readonly IAmAnInboxSync _inbox; + private SubscriberRegistry _subscriberRegistry; public PipelineGlobalInboxContextTests() { _inbox = new InMemoryInbox(new FakeTimeProvider()); - var registry = new SubscriberRegistry(); - registry.Register(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.Register(); var container = new ServiceCollection(); container.AddTransient(); @@ -41,7 +43,7 @@ public PipelineGlobalInboxContextTests() scope: InboxScope.All, context: (handlerType) => CONTEXT_KEY); - _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder((IAmAHandlerFactorySync)handlerFactory, inboxConfiguration); PipelineBuilder.ClearPipelineCache(); } @@ -50,7 +52,8 @@ public PipelineGlobalInboxContextTests() public void When_Building_A_Pipeline_With_Global_inbox() { //act - _chainOfResponsibility = _chainBuilder.Build(_requestContext); + var observers = _subscriberRegistry.Get(); + _chainOfResponsibility = observers.Select(o => _chainBuilder.Build(o, _requestContext)); var firstHandler = _chainOfResponsibility.First(); var myCommmand = new MyCommand(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Sync_Pipeline_That_Has_Async_Handlers.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Sync_Pipeline_That_Has_Async_Handlers.cs index 3c5f50d7a8..8f038d22bf 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Sync_Pipeline_That_Has_Async_Handlers.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Sync_Pipeline_That_Has_Async_Handlers.cs @@ -39,11 +39,12 @@ public class PipelineMixedHandlersTests : IDisposable private readonly PipelineBuilder _pipelineBuilder; private IHandleRequests _pipeline; private Exception _exception; + private SubscriberRegistry _subscriberRegistry; public PipelineMixedHandlersTests() { - var registry = new SubscriberRegistry(); - registry.Register(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.Register(); var container = new ServiceCollection(); container.AddTransient(); @@ -52,7 +53,7 @@ public PipelineMixedHandlersTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory); + _pipelineBuilder = new PipelineBuilder((IAmAHandlerFactorySync)handlerFactory); PipelineBuilder.ClearPipelineCache(); } @@ -60,7 +61,8 @@ public PipelineMixedHandlersTests() [Fact] public void When_Building_A_Sync_Pipeline_That_Has_Async_Handlers() { - _exception = Catch.Exception(() => _pipeline = _pipelineBuilder.Build(new RequestContext()).First()); + var observers = _subscriberRegistry.Get(); + _exception = Catch.Exception(() => _pipeline = _pipelineBuilder.Build(observers.First(), new RequestContext())); _exception.Should().NotBeNull(); _exception.Should().BeOfType(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_ForiegnAttribues.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_ForiegnAttribues.cs index 3c3a1645dd..46a6b03dd7 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_ForiegnAttribues.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_ForiegnAttribues.cs @@ -14,11 +14,12 @@ public class PipelineForiegnAttributesAsyncTests :IDisposable { private readonly PipelineBuilder _pipeline_Builder; private IHandleRequestsAsync _pipeline; + private SubscriberRegistry _subscriberRegistry; public PipelineForiegnAttributesAsyncTests() { - var registry = new SubscriberRegistry(); - registry.RegisterAsync(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.RegisterAsync(); var container = new ServiceCollection(); @@ -29,14 +30,15 @@ public PipelineForiegnAttributesAsyncTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipeline_Builder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory); + _pipeline_Builder = new PipelineBuilder((IAmAHandlerFactoryAsync)handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_Building_An_Async_Pipeline_Allow_ForeignAttributes() { - _pipeline = _pipeline_Builder.BuildAsync(new RequestContext(), false).First(); + var observers = _subscriberRegistry.Get(); + _pipeline = _pipeline_Builder.BuildAsync(observers.First(), new RequestContext(), false); TraceFilters().ToString().Should().Be("MyValidationHandlerAsync`1|MyObsoleteCommandHandlerAsync|MyLoggingHandlerAsync`1|"); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_Pre_And_Post_Tasks.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_Pre_And_Post_Tasks.cs index 7e45dfc9a5..e304ff6c54 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_Pre_And_Post_Tasks.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_Pre_And_Post_Tasks.cs @@ -13,11 +13,12 @@ public class PipelinePreAndPostFiltersAsyncTests : IDisposable { private readonly PipelineBuilder _pipelineBuilder; private IHandleRequestsAsync _pipeline; + private SubscriberRegistry _subscriberRegistry; public PipelinePreAndPostFiltersAsyncTests() { - var registry = new SubscriberRegistry(); - registry.RegisterAsync(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.RegisterAsync(); var container = new ServiceCollection(); container.AddTransient(); @@ -27,14 +28,15 @@ public PipelinePreAndPostFiltersAsyncTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder(registry,(IAmAHandlerFactoryAsync)handlerFactory); + _pipelineBuilder = new PipelineBuilder((IAmAHandlerFactoryAsync)handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] private void When_Building_An_Async_Pipeline_Allow_Pre_And_Post_Tasks() { - _pipeline = _pipelineBuilder.BuildAsync(new RequestContext(), false).First(); + var observers = _subscriberRegistry.Get(); + _pipeline = _pipelineBuilder.BuildAsync(observers.First(), new RequestContext(), false); TraceFilters().ToString().Should().Be("MyValidationHandlerAsync`1|MyPreAndPostDecoratedHandlerAsync|MyLoggingHandlerAsync`1|"); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Failures_Should_Be_ConfigurationErrors.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Failures_Should_Be_ConfigurationErrors.cs index 638871d7bc..7fd584b16f 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Failures_Should_Be_ConfigurationErrors.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Failures_Should_Be_ConfigurationErrors.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using FluentAssertions; using Paramore.Brighter.Core.Tests.CommandProcessors.TestDoubles; using Paramore.Brighter.Core.Tests.TestHelpers; @@ -10,24 +11,26 @@ public class BuildPipelineFaultsAsync { private readonly PipelineBuilder _chainBuilder; private readonly RequestContext _requestContext; + private SubscriberRegistry _subscriberRegistry; public BuildPipelineFaultsAsync() { - var registry = new SubscriberRegistry(); - registry.RegisterAsync(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.RegisterAsync(); //We'll simulate an IoC error IAmAHandlerFactoryAsync handlerFactory = new SimpleHandlerFactoryAsync(_ => throw new InvalidOperationException("Could no create handler")); _requestContext = new RequestContext(); - _chainBuilder = new PipelineBuilder(registry, handlerFactory); + _chainBuilder = new PipelineBuilder(handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_Building_A_Pipeline_Failures_Should_Be_ConfigurationErrors() { - var exception = Catch.Exception(() => _chainBuilder.BuildAsync(_requestContext, false)); + var observers = _subscriberRegistry.Get(); + var exception = Catch.Exception(() => _chainBuilder.BuildAsync(observers.First(), _requestContext, false)); exception.Should().NotBeNull(); exception.Should().BeOfType(); exception.InnerException.Should().BeOfType(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Preserve_The_Order.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Preserve_The_Order.cs index fbf4f2a3bc..f087984879 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Preserve_The_Order.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Preserve_The_Order.cs @@ -38,11 +38,12 @@ public class PipelineOrderingAsyncTests: IDisposable { private readonly PipelineBuilder _pipeline_Builder; private IHandleRequestsAsync _pipeline; + private SubscriberRegistry _subscriberRegistry; public PipelineOrderingAsyncTests() { - var registry = new SubscriberRegistry(); - registry.RegisterAsync(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.RegisterAsync(); var container = new ServiceCollection(); container.AddTransient(); @@ -52,14 +53,15 @@ public PipelineOrderingAsyncTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipeline_Builder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory); + _pipeline_Builder = new PipelineBuilder((IAmAHandlerFactoryAsync)handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_Building_An_Async_Pipeline_Preserve_The_Order() { - _pipeline = _pipeline_Builder.BuildAsync(new RequestContext(), false).First(); + var observers = _subscriberRegistry.Get(); + _pipeline = _pipeline_Builder.BuildAsync(observers.First(), new RequestContext(), false); PipelineTracer().ToString().Should().Be("MyLoggingHandlerAsync`1|MyValidationHandlerAsync`1|MyDoubleDecoratedHandlerAsync|"); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_That_Has_Sync_Handlers.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_That_Has_Sync_Handlers.cs index 6f4f05617b..86647f8409 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_That_Has_Sync_Handlers.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_That_Has_Sync_Handlers.cs @@ -15,11 +15,12 @@ public class PipelineMixedHandlersAsyncTests : IDisposable private readonly PipelineBuilder _pipelineBuilder; private IHandleRequestsAsync _pipeline; private Exception _exception; + private SubscriberRegistry _subscriberRegistry; public PipelineMixedHandlersAsyncTests() { - var registry = new SubscriberRegistry(); - registry.RegisterAsync(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.RegisterAsync(); var container = new ServiceCollection(); container.AddTransient(); @@ -29,14 +30,15 @@ public PipelineMixedHandlersAsyncTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory); + _pipelineBuilder = new PipelineBuilder((IAmAHandlerFactoryAsync)handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_Building_An_Async_Pipeline_That_Has_Sync_Handlers() { - _exception = Catch.Exception(() => _pipeline = _pipelineBuilder.BuildAsync(new RequestContext(), false).First()); + var observers = _subscriberRegistry.Get(); + _exception = Catch.Exception(() => _pipeline = _pipelineBuilder.BuildAsync(observers.First(), new RequestContext(), false)); _exception.Should().NotBeNull(); _exception.Should().BeOfType(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Hander_That_Has_Dependencies.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Hander_That_Has_Dependencies.cs index 8f52f7b0d1..b273b1ae7a 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Hander_That_Has_Dependencies.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Hander_That_Has_Dependencies.cs @@ -12,22 +12,24 @@ public class PipelineWithHandlerDependenciesTests : IDisposable { private readonly PipelineBuilder _pipelineBuilder; private IHandleRequests _pipeline; + private SubscriberRegistry _subscriberRegistry; public PipelineWithHandlerDependenciesTests() { - var registry = new SubscriberRegistry(); - registry.Register(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.Register(); var handlerFactory = new SimpleHandlerFactorySync(_ => new MyDependentCommandHandler(new FakeRepository(new FakeSession()))); - _pipelineBuilder = new PipelineBuilder(registry, handlerFactory); + _pipelineBuilder = new PipelineBuilder(handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_Finding_A_Handler_That_Has_Dependencies() { - _pipeline = _pipelineBuilder.Build(new RequestContext()).First(); + var observers = _subscriberRegistry.Get(); + _pipeline = _pipelineBuilder.Build(observers.First(), new RequestContext()); // _should_return_the_command_handler_as_the_implicit_handler _pipeline.Should().BeOfType(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command.cs index a17ae10d33..b0a4244c50 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command.cs @@ -35,21 +35,23 @@ public class PipelineBuildForCommandTests : IDisposable { private readonly PipelineBuilder _pipelineBuilder; private IHandleRequests _pipeline; + private SubscriberRegistry _subscriberRegistry; public PipelineBuildForCommandTests() { - var registry = new SubscriberRegistry(); - registry.Register(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.Register(); var handlerFactory = new SimpleHandlerFactorySync(_ => new MyCommandHandler()); - _pipelineBuilder = new PipelineBuilder(registry, handlerFactory); + _pipelineBuilder = new PipelineBuilder(handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_Finding_A_Handler_For_A_Command() { - _pipeline = _pipelineBuilder.Build(new RequestContext()).First(); + var observers = _subscriberRegistry.Get(); + _pipeline = _pipelineBuilder.Build(observers.First(), new RequestContext()); //_should_return_the_my_command_handler_as_the_implicit_handler _pipeline.Should().BeOfType(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_We_Have_Exercised_The_Pipeline_Cleanup_Its_Handlers.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_We_Have_Exercised_The_Pipeline_Cleanup_Its_Handlers.cs index fa681533b6..fba0473330 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_We_Have_Exercised_The_Pipeline_Cleanup_Its_Handlers.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_We_Have_Exercised_The_Pipeline_Cleanup_Its_Handlers.cs @@ -11,21 +11,26 @@ public class PipelineCleanupTests : IDisposable { private readonly PipelineBuilder _pipelineBuilder; private static string s_released; + private SubscriberRegistry _subscriberRegistry; public PipelineCleanupTests() { s_released = string.Empty; - var registry = new SubscriberRegistry(); - registry.Register(); - registry.Register>(); + _subscriberRegistry = new SubscriberRegistry(); + _subscriberRegistry.Register(); + _subscriberRegistry.Register>(); var handlerFactory = new CheapHandlerFactorySync(); - _pipelineBuilder = new PipelineBuilder(registry, handlerFactory); + _pipelineBuilder = new PipelineBuilder(handlerFactory); PipelineBuilder.ClearPipelineCache(); - _pipelineBuilder.Build(new RequestContext()).Any(); + var observers = _subscriberRegistry.Get(); + foreach (var observer in observers) + { + _pipelineBuilder.Build(observer, new RequestContext()); + } } [Fact] From 97b74f52811223c5f08fb739d286871f5a80451e Mon Sep 17 00:00:00 2001 From: Paul Reardon Date: Fri, 3 Jan 2025 20:30:58 +0000 Subject: [PATCH 2/8] Add scoping to the Handler Factories --- .../ServiceProviderHandlerFactory.cs | 41 ++++++++++++++++--- .../Ports/ControlBusHandlerFactory.cs | 6 ++- src/Paramore.Brighter/AsyncHandlerFactory.cs | 4 +- src/Paramore.Brighter/CommandProcessor.cs | 1 + src/Paramore.Brighter/HandlerFactory.cs | 4 +- src/Paramore.Brighter/HandlerLifetimeScope.cs | 4 +- .../IAmAHandlerFactoryAsync.cs | 7 +++- .../IAmAHandlerFactorySync.cs | 8 +++- src/Paramore.Brighter/PipelineBuilder.cs | 12 +++--- .../SimpleHandlerFactoryAsync.cs | 6 ++- .../SimpleHandlerFactorySync.cs | 4 +- .../TestDoubles/QuickHandlerFactory.cs | 4 +- .../TestDoubles/QuickHandlerFactoryAsync.cs | 4 +- ...cised_The_Pipeline_Cleanup_Its_Handlers.cs | 4 +- ..._Limit_Total_Writes_To_OutBox_In_Window.cs | 4 +- .../When_Posting_With_A_Default_Policy.cs | 4 +- .../TestDoubles/QuickHandlerFactory.cs | 4 +- .../TestDoubles/QuickHandlerFactoryAsync.cs | 4 +- 18 files changed, 83 insertions(+), 42 deletions(-) diff --git a/src/Paramore.Brighter.Extensions.DependencyInjection/ServiceProviderHandlerFactory.cs b/src/Paramore.Brighter.Extensions.DependencyInjection/ServiceProviderHandlerFactory.cs index b9dff37668..66b97053e9 100644 --- a/src/Paramore.Brighter.Extensions.DependencyInjection/ServiceProviderHandlerFactory.cs +++ b/src/Paramore.Brighter.Extensions.DependencyInjection/ServiceProviderHandlerFactory.cs @@ -23,6 +23,7 @@ THE SOFTWARE. */ #endregion using System; +using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; namespace Paramore.Brighter.Extensions.DependencyInjection @@ -34,6 +35,7 @@ public class ServiceProviderHandlerFactory : IAmAHandlerFactorySync, IAmAHandler { private readonly IServiceProvider _serviceProvider; private readonly bool _isTransient; + private readonly Dictionary _scopes = new Dictionary(); /// /// Constructs a factory that uses the .NET IoC container as the factory @@ -51,10 +53,17 @@ public ServiceProviderHandlerFactory(IServiceProvider serviceProvider) /// Lifetime is set during registration /// /// The type of handler to request + /// The brighter Handler lifetime /// An instantiated request handler - IHandleRequests IAmAHandlerFactorySync.Create(Type handlerType) + IHandleRequests IAmAHandlerFactorySync.Create(Type handlerType, IAmALifetime lifetime) { - return (IHandleRequests)_serviceProvider.GetService(handlerType); + if (!_isTransient) + return (IHandleRequests)_serviceProvider.GetService(handlerType); + + if (!_scopes.ContainsKey(lifetime)) + _scopes.Add(lifetime, _serviceProvider.CreateScope()); + + return (IHandleRequests)_scopes[lifetime].ServiceProvider.GetService(handlerType); } /// @@ -62,30 +71,50 @@ IHandleRequests IAmAHandlerFactorySync.Create(Type handlerType) /// Lifetime is set during registration /// /// The type of handler to request + /// The brighter Handler lifetime /// An instantiated request handler - IHandleRequestsAsync IAmAHandlerFactoryAsync.Create(Type handlerType) + IHandleRequestsAsync IAmAHandlerFactoryAsync.Create(Type handlerType, IAmALifetime lifetime) { - return (IHandleRequestsAsync)_serviceProvider.GetService(handlerType); + if (!_isTransient) + return (IHandleRequestsAsync)_serviceProvider.GetService(handlerType); + + if (!_scopes.ContainsKey(lifetime)) + _scopes.Add(lifetime, _serviceProvider.CreateScope()); + + return (IHandleRequestsAsync)_scopes[lifetime].ServiceProvider.GetService(handlerType); } /// /// Release the request handler - actual behavior depends on lifetime, we only dispose if we are transient /// /// - public void Release(IHandleRequests handler) + /// The brighter Handler lifetime + public void Release(IHandleRequests handler, IAmALifetime lifetime) { if (!_isTransient) return; var disposal = handler as IDisposable; disposal?.Dispose(); + + ReleaseScope(lifetime); } - public void Release(IHandleRequestsAsync handler) + public void Release(IHandleRequestsAsync handler, IAmALifetime lifetime) { if (!_isTransient) return; var disposal = handler as IDisposable; disposal?.Dispose(); + ReleaseScope(lifetime); + } + + private void ReleaseScope(IAmALifetime lifetime) + { + if(!_scopes.TryGetValue(lifetime, out IServiceScope scope)) + return; + + scope.Dispose(); + _scopes.Remove(lifetime); } } } diff --git a/src/Paramore.Brighter.ServiceActivator/Ports/ControlBusHandlerFactory.cs b/src/Paramore.Brighter.ServiceActivator/Ports/ControlBusHandlerFactory.cs index f4b8df83f0..3a85533dd1 100644 --- a/src/Paramore.Brighter.ServiceActivator/Ports/ControlBusHandlerFactory.cs +++ b/src/Paramore.Brighter.ServiceActivator/Ports/ControlBusHandlerFactory.cs @@ -18,8 +18,9 @@ public ControlBusHandlerFactorySync(IDispatcher worker, Func /// Type of the handler. + /// The Brighter Handler Lifetime /// IHandleRequests. - public IHandleRequests Create(Type handlerType) + public IHandleRequests Create(Type handlerType, IAmALifetime lifetime) { if (handlerType == typeof(ConfigurationCommandHandler)) return new ConfigurationCommandHandler(_worker); @@ -34,7 +35,8 @@ public IHandleRequests Create(Type handlerType) /// Releases the specified handler. /// /// The handler. - public void Release(IHandleRequests handler) + /// The Brighter Handler Lifetime + public void Release(IHandleRequests handler, IAmALifetime lifetime) { } } diff --git a/src/Paramore.Brighter/AsyncHandlerFactory.cs b/src/Paramore.Brighter/AsyncHandlerFactory.cs index 6495cbd705..8f0690a916 100644 --- a/src/Paramore.Brighter/AsyncHandlerFactory.cs +++ b/src/Paramore.Brighter/AsyncHandlerFactory.cs @@ -39,11 +39,11 @@ internal static class AsyncHandlerFactory /// The request context. /// . /// The type of the request. - public static IHandleRequestsAsync CreateAsyncRequestHandler(this IAmAHandlerFactoryAsync factory, RequestHandlerAttribute attribute, IRequestContext requestContext) + public static IHandleRequestsAsync CreateAsyncRequestHandler(this IAmAHandlerFactoryAsync factory, RequestHandlerAttribute attribute, IRequestContext requestContext, IAmALifetime lifetime) where TRequest : class, IRequest { var handlerType = attribute.GetHandlerType().MakeGenericType(typeof(TRequest)); - var handler = (IHandleRequestsAsync)factory.Create(handlerType); + var handler = (IHandleRequestsAsync)factory.Create(handlerType, lifetime); if (handler is null) throw new ConfigurationException($"Could not create handler {handlerType} from {factory}"); diff --git a/src/Paramore.Brighter/CommandProcessor.cs b/src/Paramore.Brighter/CommandProcessor.cs index 363589e74f..0d96db3bb0 100644 --- a/src/Paramore.Brighter/CommandProcessor.cs +++ b/src/Paramore.Brighter/CommandProcessor.cs @@ -355,6 +355,7 @@ public void Publish(T @event, RequestContext? requestContext = null) where T { s_logger.LogInformation("Building send pipeline for event: {EventType} {Id}", @event.GetType(), @event.Id); + using var builder = new PipelineBuilder(_handlerFactorySync, _inboxConfiguration); var handleRequests = builder.Build(observer, context); diff --git a/src/Paramore.Brighter/HandlerFactory.cs b/src/Paramore.Brighter/HandlerFactory.cs index e96d333bfc..ed64baf8ff 100644 --- a/src/Paramore.Brighter/HandlerFactory.cs +++ b/src/Paramore.Brighter/HandlerFactory.cs @@ -41,10 +41,10 @@ public HandlerFactory(RequestHandlerAttribute attribute, IAmAHandlerFactorySync _messageType = typeof(TRequest); } - public IHandleRequests CreateRequestHandler() + public IHandleRequests CreateRequestHandler(IAmALifetime lifetime) { var handlerType = _attribute.GetHandlerType().MakeGenericType(_messageType); - var handler = (IHandleRequests)_factorySync.Create(handlerType); + var handler = (IHandleRequests)_factorySync.Create(handlerType, lifetime); if (handler is null) throw new ConfigurationException($"Could not create handler {handlerType} from {_factorySync}"); diff --git a/src/Paramore.Brighter/HandlerLifetimeScope.cs b/src/Paramore.Brighter/HandlerLifetimeScope.cs index ae26c58f46..6f0be0faf9 100644 --- a/src/Paramore.Brighter/HandlerLifetimeScope.cs +++ b/src/Paramore.Brighter/HandlerLifetimeScope.cs @@ -76,14 +76,14 @@ public void Dispose() _trackedObjects.Each((trackedItem) => { //free disposable items - _handlerFactorySync?.Release(trackedItem); + _handlerFactorySync?.Release(trackedItem, this); s_logger.LogDebug("Releasing handler instance {InstanceHashCode} of type {HandlerType}", trackedItem.GetHashCode(), trackedItem.GetType()); }); _trackedAsyncObjects.Each(trackedItem => { //free disposable items - _asyncHandlerFactory?.Release(trackedItem); + _asyncHandlerFactory?.Release(trackedItem, this); s_logger.LogDebug("Releasing async handler instance {InstanceHashCode} of type {HandlerType}", trackedItem.GetHashCode(), trackedItem.GetType()); }); diff --git a/src/Paramore.Brighter/IAmAHandlerFactoryAsync.cs b/src/Paramore.Brighter/IAmAHandlerFactoryAsync.cs index fbb8479078..4f857bc953 100644 --- a/src/Paramore.Brighter/IAmAHandlerFactoryAsync.cs +++ b/src/Paramore.Brighter/IAmAHandlerFactoryAsync.cs @@ -39,12 +39,15 @@ public interface IAmAHandlerFactoryAsync : IAmAHandlerFactory /// Creates the specified async handler type. /// /// Type of the handler. + /// The brighter Handler lifetime /// IHandleRequestsAsync. - IHandleRequestsAsync Create(Type handlerType); + IHandleRequestsAsync Create(Type handlerType, IAmALifetime lifetime); + /// /// Releases the specified async handler. /// /// The handler. - void Release(IHandleRequestsAsync? handler); + /// The brighter Handler lifetime. + void Release(IHandleRequestsAsync? handler, IAmALifetime lifetime); } } diff --git a/src/Paramore.Brighter/IAmAHandlerFactorySync.cs b/src/Paramore.Brighter/IAmAHandlerFactorySync.cs index c78c1a7634..aae6bcbad3 100644 --- a/src/Paramore.Brighter/IAmAHandlerFactorySync.cs +++ b/src/Paramore.Brighter/IAmAHandlerFactorySync.cs @@ -39,12 +39,16 @@ public interface IAmAHandlerFactorySync : IAmAHandlerFactory /// Creates the specified handler type. /// /// Type of the handler. + /// The Brighter handler Lifetime /// IHandleRequests. - IHandleRequests Create(Type handlerType); + IHandleRequests Create(Type handlerType, IAmALifetime lifetime); + /// /// Releases the specified handler. /// /// The handler. - void Release(IHandleRequests handler); + /// The Brighter handler Lifetime + void Release(IHandleRequests handler, IAmALifetime lifetime); + } } diff --git a/src/Paramore.Brighter/PipelineBuilder.cs b/src/Paramore.Brighter/PipelineBuilder.cs index cb4f0153a3..dd932fd1ff 100644 --- a/src/Paramore.Brighter/PipelineBuilder.cs +++ b/src/Paramore.Brighter/PipelineBuilder.cs @@ -78,7 +78,7 @@ public IHandleRequests Build(Type type, IRequestContext requestContext try { - var handler = (RequestHandler)_handlerFactorySync.Create(type); + var handler = (RequestHandler)_handlerFactorySync.Create(type, _instanceScope); var pipeline = BuildPipeline(handler, requestContext); pipeline.AddToLifetime(_instanceScope); return pipeline; @@ -154,7 +154,7 @@ public IHandleRequestsAsync BuildAsync(Type type, IRequestContext requ try { - var handler = (RequestHandlerAsync)_asyncHandlerFactory.Create(type); + var handler = (RequestHandlerAsync)_asyncHandlerFactory.Create(type, _instanceScope); var pipeline = BuildAsyncPipeline(handler, requestContext, continueOnCapturedContext); pipeline.AddToLifetime(_instanceScope); @@ -265,7 +265,7 @@ private void AppendToPipeline(IEnumerable attributes, I if (handlerType.GetInterfaces().Contains(typeof(IHandleRequests))) { var decorator = - new HandlerFactory(attribute, _handlerFactorySync!, requestContext).CreateRequestHandler(); + new HandlerFactory(attribute, _handlerFactorySync!, requestContext).CreateRequestHandler(_instanceScope); lastInPipeline.SetSuccessor(decorator); lastInPipeline = decorator; } @@ -285,7 +285,7 @@ private void AppendToAsyncPipeline(IEnumerable attribut var handlerType = attribute.GetHandlerType(); if (handlerType.GetInterfaces().Contains(typeof(IHandleRequestsAsync))) { - var decorator = _asyncHandlerFactory!.CreateAsyncRequestHandler(attribute, requestContext); + var decorator = _asyncHandlerFactory!.CreateAsyncRequestHandler(attribute, requestContext, _instanceScope); lastInPipeline.SetSuccessor(decorator); lastInPipeline = decorator; } @@ -320,7 +320,7 @@ private IHandleRequests PushOntoPipeline(IEnumerable(attribute, _handlerFactorySync!, requestContext).CreateRequestHandler(); + new HandlerFactory(attribute, _handlerFactorySync!, requestContext).CreateRequestHandler(_instanceScope); decorator.SetSuccessor(lastInPipeline); lastInPipeline = decorator; } @@ -340,7 +340,7 @@ private IHandleRequestsAsync PushOntoAsyncPipeline(IEnumerable(attribute, requestContext); + var decorator = _asyncHandlerFactory!.CreateAsyncRequestHandler(attribute, requestContext, _instanceScope); decorator.ContinueOnCapturedContext = continueOnCapturedContext; decorator.SetSuccessor(lastInPipeline); lastInPipeline = decorator; diff --git a/src/Paramore.Brighter/SimpleHandlerFactoryAsync.cs b/src/Paramore.Brighter/SimpleHandlerFactoryAsync.cs index 03176c27c3..8e7685f817 100644 --- a/src/Paramore.Brighter/SimpleHandlerFactoryAsync.cs +++ b/src/Paramore.Brighter/SimpleHandlerFactoryAsync.cs @@ -36,8 +36,9 @@ public class SimpleHandlerFactoryAsync(Func factoryM /// Create a handler for a given request type /// /// The type of request + /// The Brighter Handler Lifetime /// - public IHandleRequestsAsync Create(Type handlerType) + public IHandleRequestsAsync Create(Type handlerType, IAmALifetime lifetime) { return factoryMethod(handlerType); } @@ -46,7 +47,8 @@ public IHandleRequestsAsync Create(Type handlerType) /// Dispose of the handler /// /// The handler to dispose - public void Release(IHandleRequestsAsync? handler) + /// The Brighter Handler Lifetime + public void Release(IHandleRequestsAsync? handler, IAmALifetime lifetime) { if (handler is IDisposable disposable) { diff --git a/src/Paramore.Brighter/SimpleHandlerFactorySync.cs b/src/Paramore.Brighter/SimpleHandlerFactorySync.cs index a64bc1ded5..9908314214 100644 --- a/src/Paramore.Brighter/SimpleHandlerFactorySync.cs +++ b/src/Paramore.Brighter/SimpleHandlerFactorySync.cs @@ -32,12 +32,12 @@ namespace Paramore.Brighter /// public class SimpleHandlerFactorySync(Func factoryMethod) : IAmAHandlerFactorySync { - public IHandleRequests Create(Type handlerType) + public IHandleRequests Create(Type handlerType, IAmALifetime lifetime) { return factoryMethod(handlerType); } - public void Release(IHandleRequests handler) + public void Release(IHandleRequests handler, IAmALifetime lifetime) { var disposable = handler as IDisposable; disposable?.Dispose(); diff --git a/tests/Paramore.Brighter.AWS.Tests/TestDoubles/QuickHandlerFactory.cs b/tests/Paramore.Brighter.AWS.Tests/TestDoubles/QuickHandlerFactory.cs index 4c76f19851..208a348d47 100644 --- a/tests/Paramore.Brighter.AWS.Tests/TestDoubles/QuickHandlerFactory.cs +++ b/tests/Paramore.Brighter.AWS.Tests/TestDoubles/QuickHandlerFactory.cs @@ -10,11 +10,11 @@ public QuickHandlerFactory(Func handlerAction) { _handlerAction = handlerAction; } - public IHandleRequests Create(Type handlerType) + public IHandleRequests Create(Type handlerType, IAmALifetime lifetime) { return _handlerAction(); } - public void Release(IHandleRequests handler) { } + public void Release(IHandleRequests handler, IAmALifetime lifetime) { } } } diff --git a/tests/Paramore.Brighter.AWS.Tests/TestDoubles/QuickHandlerFactoryAsync.cs b/tests/Paramore.Brighter.AWS.Tests/TestDoubles/QuickHandlerFactoryAsync.cs index e2a2cc74a5..35ccc61458 100644 --- a/tests/Paramore.Brighter.AWS.Tests/TestDoubles/QuickHandlerFactoryAsync.cs +++ b/tests/Paramore.Brighter.AWS.Tests/TestDoubles/QuickHandlerFactoryAsync.cs @@ -10,12 +10,12 @@ public QuickHandlerFactoryAsync(Func handlerFactory) _handlerFactory = handlerFactory; } - public IHandleRequestsAsync Create(Type handlerType) + public IHandleRequestsAsync Create(Type handlerType, IAmALifetime lifetime) { return _handlerFactory(); } - public void Release(IHandleRequestsAsync handler) + public void Release(IHandleRequestsAsync handler, IAmALifetime lifetime) { // Implement any necessary cleanup logic here } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_We_Have_Exercised_The_Pipeline_Cleanup_Its_Handlers.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_We_Have_Exercised_The_Pipeline_Cleanup_Its_Handlers.cs index fba0473330..e4633e860f 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_We_Have_Exercised_The_Pipeline_Cleanup_Its_Handlers.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_We_Have_Exercised_The_Pipeline_Cleanup_Its_Handlers.cs @@ -53,7 +53,7 @@ public void Dispose() internal class CheapHandlerFactorySync : IAmAHandlerFactorySync { - public IHandleRequests Create(Type handlerType) + public IHandleRequests Create(Type handlerType, IAmALifetime lifetime) { if (handlerType == typeof(MyPreAndPostDecoratedHandler)) { @@ -70,7 +70,7 @@ public IHandleRequests Create(Type handlerType) return null; } - public void Release(IHandleRequests handler) + public void Release(IHandleRequests handler, IAmALifetime lifetime) { var disposable = handler as IDisposable; disposable?.Dispose(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Fails_Limit_Total_Writes_To_OutBox_In_Window.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Fails_Limit_Total_Writes_To_OutBox_In_Window.cs index a81fd1d745..871ee78e84 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Fails_Limit_Total_Writes_To_OutBox_In_Window.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_Fails_Limit_Total_Writes_To_OutBox_In_Window.cs @@ -124,12 +124,12 @@ public void Dispose() internal class EmptyHandlerFactorySync : IAmAHandlerFactorySync { - public IHandleRequests Create(Type handlerType) + public IHandleRequests Create(Type handlerType, IAmALifetime lifetime) { return null; } - public void Release(IHandleRequests handler) {} + public void Release(IHandleRequests handler, IAmALifetime lifetime) {} } } } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_With_A_Default_Policy.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_With_A_Default_Policy.cs index 766cddefaf..06a832047f 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_With_A_Default_Policy.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Post/When_Posting_With_A_Default_Policy.cs @@ -109,12 +109,12 @@ public void Dispose() internal class EmptyHandlerFactorySync : IAmAHandlerFactorySync { - public IHandleRequests Create(Type handlerType) + public IHandleRequests Create(Type handlerType, IAmALifetime lifetime) { return null; } - public void Release(IHandleRequests handler) {} + public void Release(IHandleRequests handler, IAmALifetime lifetime) {} } } } diff --git a/tests/Paramore.Brighter.RMQ.Tests/TestDoubles/QuickHandlerFactory.cs b/tests/Paramore.Brighter.RMQ.Tests/TestDoubles/QuickHandlerFactory.cs index a9ca3e4ed7..57734aa997 100644 --- a/tests/Paramore.Brighter.RMQ.Tests/TestDoubles/QuickHandlerFactory.cs +++ b/tests/Paramore.Brighter.RMQ.Tests/TestDoubles/QuickHandlerFactory.cs @@ -4,10 +4,10 @@ namespace Paramore.Brighter.RMQ.Tests.TestDoubles; internal class QuickHandlerFactory(Func handlerAction) : IAmAHandlerFactorySync { - public IHandleRequests Create(Type handlerType) + public IHandleRequests Create(Type handlerType, IAmALifetime lifetime) { return handlerAction(); } - public void Release(IHandleRequests handler) { } + public void Release(IHandleRequests handler, IAmALifetime lifetime) { } } diff --git a/tests/Paramore.Brighter.RMQ.Tests/TestDoubles/QuickHandlerFactoryAsync.cs b/tests/Paramore.Brighter.RMQ.Tests/TestDoubles/QuickHandlerFactoryAsync.cs index 6d18972646..4a1495912c 100644 --- a/tests/Paramore.Brighter.RMQ.Tests/TestDoubles/QuickHandlerFactoryAsync.cs +++ b/tests/Paramore.Brighter.RMQ.Tests/TestDoubles/QuickHandlerFactoryAsync.cs @@ -4,10 +4,10 @@ namespace Paramore.Brighter.RMQ.Tests.TestDoubles; internal class QuickHandlerFactoryAsync(Func handlerAction) : IAmAHandlerFactoryAsync { - public IHandleRequestsAsync Create(Type handlerType) + public IHandleRequestsAsync Create(Type handlerType, IAmALifetime lifetime) { return handlerAction(); } - public void Release(IHandleRequestsAsync handler) { } + public void Release(IHandleRequestsAsync handler, IAmALifetime lifetime) { } } From 14f5a89428c4a20474710f0a411726ee751be6a4 Mon Sep 17 00:00:00 2001 From: Paul Reardon Date: Fri, 3 Jan 2025 20:52:22 +0000 Subject: [PATCH 3/8] Remove Command Processor provider As scopes are now done in the Handler Factories Command Processor Providers are no longer needed --- .../Hosting/HeartbeatHostedService.cs | 7 +-- .../ScopedCommandProcessorProvider.cs | 34 ------------ .../ServiceCollectionExtensions.cs | 14 +---- .../CommandProcessorProvider.cs | 55 ------------------- .../ConsumerFactory.cs | 14 ++--- .../ControlBus/ControlBusReceiverBuilder.cs | 3 +- .../DispatchBuilder.cs | 26 ++++----- .../Dispatcher.cs | 52 +++--------------- .../IAmACommandProcessorProvider.cs | 13 ----- .../MessagePump.cs | 15 ++--- .../Proactor.cs | 15 ++--- .../Reactor.cs | 13 ++--- ...n_throwing_defer_action_respect_redrive.cs | 3 +- ...wing_defer_action_respect_redrive_async.cs | 3 +- ...ling_A_Server_Via_The_Command_Processor.cs | 4 +- ...y_until_connection_re_established_async.cs | 3 +- ...y_until_connection_re_established_async.cs | 3 +- ...essage_is_requeued_until_rejected_async.cs | 3 +- ...d_exception_Then_message_is_acked_async.cs | 3 +- ...ceptable_message_limit_is_reached_async.cs | 3 +- ...e_fails_to_be_mapped_to_a_request_async.cs | 3 +- ...patched_it_should_reach_a_handler_async.cs | 4 +- ...threshold_for_commands_has_been_reached.cs | 3 +- ...t_threshold_for_events_has_been_reached.cs | 3 +- ..._requeue_of_command_exception_is_thrown.cs | 3 +- ..._a_requeue_of_event_exception_is_thrown.cs | 3 +- ...message_is_requeued_until_rejectedAsync.cs | 3 +- ...d_exception_Then_message_is_acked_async.cs | 3 +- ..._unacceptable_message_is_recieved_async.cs | 3 +- ...ceptable_message_limit_is_reached_async.cs | 3 +- ...nel_pump_out_to_command_processor_async.cs | 3 +- ...n_a_thread_should_be_able_to_stop_async.cs | 3 +- ...d_retry_until_connection_re_established.cs | 3 +- ...d_retry_until_connection_re_established.cs | 3 +- ...Then_message_is_requeued_until_rejected.cs | 3 +- ...handled_exception_Then_message_is_acked.cs | 3 +- ...message_fails_to_be_mapped_to_a_request.cs | 3 +- ...e_unacceptable_message_limit_is_reached.cs | 3 +- ...is_dispatched_it_should_reach_a_handler.cs | 4 +- ...threshold_for_commands_has_been_reached.cs | 3 +- ...t_threshold_for_events_has_been_reached.cs | 3 +- ..._requeue_of_command_exception_is_thrown.cs | 3 +- ..._a_requeue_of_event_exception_is_thrown.cs | 3 +- ...Then_message_is_requeued_until_rejected.cs | 3 +- ...handled_exception_Then_message_is_acked.cs | 3 +- ...hen_an_unacceptable_message_is_recieved.cs | 3 +- ...n_unacceptable_message_limit_is_reached.cs | 3 +- ...a_channel_pump_out_to_command_processor.cs | 3 +- ...pump_on_a_thread_should_be_able_to_stop.cs | 3 +- ...ge_Is_Dispatched_It_Should_Begin_A_Span.cs | 4 +- ...en_There_Are_No_Messages_Close_The_Span.cs | 4 +- ...nCircuit_Channel_Failure_Close_The_Span.cs | 4 +- ...ere_Is_A_Channel_Failure_Close_The_Span.cs | 4 +- ..._There_Is_A_Quit_Message_Close_The_Span.cs | 4 +- ...An_Unacceptable_Messages_Close_The_Span.cs | 4 +- .../When_building_a_dispatcher.cs | 3 +- .../When_building_a_dispatcher_async.cs | 3 +- ...uilding_a_dispatcher_with_named_gateway.cs | 3 +- ...g_a_dispatcher_with_named_gateway_async.cs | 3 +- ...try_limits_force_a_message_onto_the_DLQ.cs | 3 +- ...mits_force_a_message_onto_the_DLQ_async.cs | 3 +- 61 files changed, 97 insertions(+), 320 deletions(-) delete mode 100644 src/Paramore.Brighter.ServiceActivator.Extensions.DependencyInjection/ScopedCommandProcessorProvider.cs delete mode 100644 src/Paramore.Brighter.ServiceActivator/CommandProcessorProvider.cs delete mode 100644 src/Paramore.Brighter.ServiceActivator/IAmACommandProcessorProvider.cs diff --git a/src/Paramore.Brighter.ServiceActivator.Control/Hosting/HeartbeatHostedService.cs b/src/Paramore.Brighter.ServiceActivator.Control/Hosting/HeartbeatHostedService.cs index a32a0c216e..7a87ccdb97 100644 --- a/src/Paramore.Brighter.ServiceActivator.Control/Hosting/HeartbeatHostedService.cs +++ b/src/Paramore.Brighter.ServiceActivator.Control/Hosting/HeartbeatHostedService.cs @@ -37,12 +37,9 @@ private void SendHeartbeat(object? state) { _logger.LogInformation("Sending Heartbeat"); - var factory = ((Dispatcher)_dispatcher).CommandProcessorFactory.Invoke(); + var commandProcessor = ((Dispatcher)_dispatcher).CommandProcessor; - factory.CreateScope(); - - HeartBeatSender.Send(factory.Get(), _dispatcher); + HeartBeatSender.Send(commandProcessor, _dispatcher); - factory.ReleaseScope(); } } diff --git a/src/Paramore.Brighter.ServiceActivator.Extensions.DependencyInjection/ScopedCommandProcessorProvider.cs b/src/Paramore.Brighter.ServiceActivator.Extensions.DependencyInjection/ScopedCommandProcessorProvider.cs deleted file mode 100644 index d3ac0fec93..0000000000 --- a/src/Paramore.Brighter.ServiceActivator.Extensions.DependencyInjection/ScopedCommandProcessorProvider.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using Microsoft.Extensions.DependencyInjection; - -namespace Paramore.Brighter.ServiceActivator.Extensions.DependencyInjection -{ - public class ScopedCommandProcessorProvider : IAmACommandProcessorProvider - { - private readonly IServiceProvider _serviceProvider; - private IServiceScope _scope; - - public ScopedCommandProcessorProvider(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } - public IAmACommandProcessor Get() - { - if (_scope != null) - return (IAmACommandProcessor)_scope.ServiceProvider.GetService(typeof(IAmACommandProcessor)); - return (IAmACommandProcessor)_serviceProvider.GetService(typeof(IAmACommandProcessor)); - } - - public void CreateScope() - { - _scope = _serviceProvider.CreateScope(); - } - - public void ReleaseScope() => Dispose(); - - public void Dispose() - { - _scope?.Dispose(); - } - } -} diff --git a/src/Paramore.Brighter.ServiceActivator.Extensions.DependencyInjection/ServiceCollectionExtensions.cs b/src/Paramore.Brighter.ServiceActivator.Extensions.DependencyInjection/ServiceCollectionExtensions.cs index 66b9b56363..c98771f526 100644 --- a/src/Paramore.Brighter.ServiceActivator.Extensions.DependencyInjection/ServiceCollectionExtensions.cs +++ b/src/Paramore.Brighter.ServiceActivator.Extensions.DependencyInjection/ServiceCollectionExtensions.cs @@ -54,23 +54,13 @@ private static Dispatcher BuildDispatcher(IServiceProvider serviceProvider) var options = serviceProvider.GetService(); - Func providerFactory; - - if (options.UseScoped) - { - providerFactory = () => new ScopedCommandProcessorProvider(serviceProvider); - } - else - { - var commandProcessor = serviceProvider.GetService(); - providerFactory = () => new CommandProcessorProvider(commandProcessor); - } + var commandProcessor = serviceProvider.GetService(); var requestContextFactory = serviceProvider.GetService(); var dispatcherBuilder = DispatchBuilder .StartNew() - .CommandProcessorFactory(providerFactory, requestContextFactory); + .CommandProcessor(commandProcessor, requestContextFactory); var messageMapperRegistry = ServiceCollectionExtensions.MessageMapperRegistry(serviceProvider); var messageTransformFactory = ServiceCollectionExtensions.TransformFactory(serviceProvider); diff --git a/src/Paramore.Brighter.ServiceActivator/CommandProcessorProvider.cs b/src/Paramore.Brighter.ServiceActivator/CommandProcessorProvider.cs deleted file mode 100644 index 55fdb8b1b8..0000000000 --- a/src/Paramore.Brighter.ServiceActivator/CommandProcessorProvider.cs +++ /dev/null @@ -1,55 +0,0 @@ -#region Licence -/* The MIT License (MIT) -Copyright © 2014 Ian Cooper - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the “Software”), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. */ - -#endregion - -namespace Paramore.Brighter.ServiceActivator -{ - public class CommandProcessorProvider : IAmACommandProcessorProvider - { - private readonly IAmACommandProcessor _commandProcessor; - - public CommandProcessorProvider(IAmACommandProcessor commandProcessor) - { - _commandProcessor = commandProcessor; - } - public void Dispose() - { - //Nothing to Dispose - } - - public IAmACommandProcessor Get() - { - return _commandProcessor; - } - - public void CreateScope() - { - //This is not Scoped - } - - public void ReleaseScope() - { - //This is not scoped - } - } -} diff --git a/src/Paramore.Brighter.ServiceActivator/ConsumerFactory.cs b/src/Paramore.Brighter.ServiceActivator/ConsumerFactory.cs index 080201fab0..77acd1633c 100644 --- a/src/Paramore.Brighter.ServiceActivator/ConsumerFactory.cs +++ b/src/Paramore.Brighter.ServiceActivator/ConsumerFactory.cs @@ -29,7 +29,7 @@ namespace Paramore.Brighter.ServiceActivator { internal class ConsumerFactory : IConsumerFactory where TRequest : class, IRequest { - private readonly IAmACommandProcessorProvider _commandProcessorProvider; + private readonly IAmACommandProcessor _commandProcessor; private readonly IAmAMessageMapperRegistry? _messageMapperRegistry; private readonly Subscription _subscription; private readonly IAmAMessageTransformerFactory? _messageTransformerFactory; @@ -41,7 +41,7 @@ internal class ConsumerFactory : IConsumerFactory where TRequest : cla private readonly IAmAMessageTransformerFactoryAsync? _messageTransformerFactoryAsync; public ConsumerFactory( - IAmACommandProcessorProvider commandProcessorProvider, + IAmACommandProcessor commandProcessor, Subscription subscription, IAmAMessageMapperRegistry messageMapperRegistry, IAmAMessageTransformerFactory? messageTransformerFactory, @@ -49,7 +49,7 @@ public ConsumerFactory( IAmABrighterTracer tracer, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) { - _commandProcessorProvider = commandProcessorProvider; + _commandProcessor = commandProcessor; _messageMapperRegistry = messageMapperRegistry; _subscription = subscription; _messageTransformerFactory = messageTransformerFactory ?? new EmptyMessageTransformerFactory(); @@ -60,7 +60,7 @@ public ConsumerFactory( } public ConsumerFactory( - IAmACommandProcessorProvider commandProcessorProvider, + IAmACommandProcessor commandProcessor, Subscription subscription, IAmAMessageMapperRegistryAsync messageMapperRegistryAsync, IAmAMessageTransformerFactoryAsync? messageTransformerFactoryAsync, @@ -68,7 +68,7 @@ public ConsumerFactory( IAmABrighterTracer tracer, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) { - _commandProcessorProvider = commandProcessorProvider; + _commandProcessor = commandProcessor; _messageMapperRegistryAsync = messageMapperRegistryAsync; _subscription = subscription; _messageTransformerFactoryAsync = messageTransformerFactoryAsync ?? new EmptyMessageTransformerFactoryAsync(); @@ -95,7 +95,7 @@ private Consumer CreateReactor() throw new ArgumentException("Subscription must have a Channel Factory in order to create a consumer."); var channel = _subscription.ChannelFactory.CreateSyncChannel(_subscription); - var messagePump = new Reactor(_commandProcessorProvider, _messageMapperRegistry, + var messagePump = new Reactor(_commandProcessor, _messageMapperRegistry, _messageTransformerFactory, _requestContextFactory, channel, _tracer, _instrumentationOptions) { Channel = channel, @@ -117,7 +117,7 @@ private Consumer CreateProactor() throw new ArgumentException("Subscription must have a Channel Factory in order to create a consumer."); var channel = _subscription.ChannelFactory.CreateAsyncChannel(_subscription); - var messagePump = new Proactor(_commandProcessorProvider, _messageMapperRegistryAsync, + var messagePump = new Proactor(_commandProcessor, _messageMapperRegistryAsync, _messageTransformerFactoryAsync, _requestContextFactory, channel, _tracer, _instrumentationOptions) { Channel = channel, diff --git a/src/Paramore.Brighter.ServiceActivator/ControlBus/ControlBusReceiverBuilder.cs b/src/Paramore.Brighter.ServiceActivator/ControlBus/ControlBusReceiverBuilder.cs index b5d2fe371d..55f92b51d4 100644 --- a/src/Paramore.Brighter.ServiceActivator/ControlBus/ControlBusReceiverBuilder.cs +++ b/src/Paramore.Brighter.ServiceActivator/ControlBus/ControlBusReceiverBuilder.cs @@ -197,8 +197,7 @@ public Dispatcher Build(string hostName) if (_channelFactory is null) throw new ArgumentException("Channel Factory must not be null"); return DispatchBuilder.StartNew() - .CommandProcessorFactory(() => - new CommandProcessorProvider(commandProcessor), new InMemoryRequestContextFactory() + .CommandProcessor(commandProcessor, new InMemoryRequestContextFactory() ) .MessageMappers(incomingMessageMapperRegistry, null, null, null) .ChannelFactory(_channelFactory) diff --git a/src/Paramore.Brighter.ServiceActivator/DispatchBuilder.cs b/src/Paramore.Brighter.ServiceActivator/DispatchBuilder.cs index 012ef3168c..722bff541b 100644 --- a/src/Paramore.Brighter.ServiceActivator/DispatchBuilder.cs +++ b/src/Paramore.Brighter.ServiceActivator/DispatchBuilder.cs @@ -35,9 +35,9 @@ namespace Paramore.Brighter.ServiceActivator /// progressive interfaces to manage the requirements for a complete Dispatcher via Intellisense in the IDE. The intent is to make it easier to /// recognize those dependencies that you need to configure /// - public class DispatchBuilder : INeedACommandProcessorFactory, INeedAChannelFactory, INeedAMessageMapper, INeedAListOfSubcriptions, INeedObservability, IAmADispatchBuilder + public class DispatchBuilder : INeedACommandProcessor, INeedAChannelFactory, INeedAMessageMapper, INeedAListOfSubcriptions, INeedObservability, IAmADispatchBuilder { - private Func? _commandProcessorFactory; + private IAmACommandProcessor? _commandProcessor; private IAmAMessageMapperRegistry? _messageMapperRegistry; private IAmAMessageMapperRegistryAsync? _messageMapperRegistryAsync; private IAmAChannelFactory? _defaultChannelFactory; @@ -54,7 +54,7 @@ private DispatchBuilder() { } /// Begins the fluent interface /// /// INeedALogger. - public static INeedACommandProcessorFactory StartNew() + public static INeedACommandProcessor StartNew() { return new DispatchBuilder(); } @@ -62,15 +62,15 @@ public static INeedACommandProcessorFactory StartNew() /// /// The command processor used to send and publish messages to handlers by the service activator. /// - /// The command processor Factory. + /// The command processor. /// The factory used to create a request synchronizationHelper for a pipeline /// INeedAMessageMapper. - public INeedAMessageMapper CommandProcessorFactory( - Func commandProcessorFactory, + public INeedAMessageMapper CommandProcessor( + IAmACommandProcessor commandProcessor, IAmARequestContextFactory requestContextFactory ) { - _commandProcessorFactory = commandProcessorFactory; + _commandProcessor = commandProcessor; _requestContextFactory = requestContextFactory; return this; } @@ -157,10 +157,10 @@ public INeedObservability Subscriptions(IEnumerable subscriptions) /// Dispatcher. public Dispatcher Build() { - if (_commandProcessorFactory is null || _subscriptions is null) + if (_commandProcessor is null || _subscriptions is null) throw new ArgumentException("Command Processor Factory and Subscription are required."); - return new Dispatcher(_commandProcessorFactory, _subscriptions, _messageMapperRegistry, + return new Dispatcher(_commandProcessor, _subscriptions, _messageMapperRegistry, _messageMapperRegistryAsync, _messageTransformerFactory, _messageTransformerFactoryAsync, _requestContextFactory, _tracer, _instrumentationOptions ); @@ -174,16 +174,16 @@ public Dispatcher Build() /// /// Interface INeedACommandProcessor /// - public interface INeedACommandProcessorFactory + public interface INeedACommandProcessor { /// /// The command processor used to send and publish messages to handlers by the service activator. /// - /// The command processor provider Factory. + /// The command processor. /// The factory used to create a request synchronizationHelper for a pipeline /// INeedAMessageMapper. - INeedAMessageMapper CommandProcessorFactory( - Func commandProcessorFactory, + INeedAMessageMapper CommandProcessor( + IAmACommandProcessor commandProcessor, IAmARequestContextFactory requestContextFactory ); } diff --git a/src/Paramore.Brighter.ServiceActivator/Dispatcher.cs b/src/Paramore.Brighter.ServiceActivator/Dispatcher.cs index 888832a409..a466d52d75 100644 --- a/src/Paramore.Brighter.ServiceActivator/Dispatcher.cs +++ b/src/Paramore.Brighter.ServiceActivator/Dispatcher.cs @@ -62,12 +62,7 @@ public class Dispatcher : IDispatcher /// Gets the command processor. /// /// The command processor. - public IAmACommandProcessor CommandProcessor { get => CommandProcessorFactory.Invoke().Get(); } - - /// - /// - /// - public Func CommandProcessorFactory { get; } + public IAmACommandProcessor CommandProcessor { get; private set; } /// /// Gets the connections. @@ -97,7 +92,7 @@ public class Dispatcher : IDispatcher /// /// Initializes a new instance of the class. /// - /// The command processor Factory. + /// The command processor we should use with the dispatcher (prefer to use Command Processor Provider for IoC Scope control /// The subscriptions. /// The message mapper registry. /// Async message mapper registry. @@ -108,7 +103,7 @@ public class Dispatcher : IDispatcher /// When creating a span for operations how noisy should the attributes be /// throws You must provide at least one type of message mapper registry public Dispatcher( - Func commandProcessorFactory, + IAmACommandProcessor commandProcessor, IEnumerable subscriptions, IAmAMessageMapperRegistry? messageMapperRegistry = null, IAmAMessageMapperRegistryAsync? messageMapperRegistryAsync = null, @@ -118,7 +113,7 @@ public Dispatcher( IAmABrighterTracer? tracer = null, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) { - CommandProcessorFactory = commandProcessorFactory; + CommandProcessor = commandProcessor; Subscriptions = subscriptions; _messageMapperRegistry = messageMapperRegistry; @@ -144,37 +139,6 @@ public Dispatcher( State = DispatcherState.DS_AWAITING; } - /// - /// Initializes a new instance of the class. - /// - /// The command processor we should use with the dispatcher (prefer to use Command Processor Provider for IoC Scope control - /// The subscriptions. - /// The message mapper registry. - /// Async message mapper registry. - /// Creates instances of Transforms - /// Creates instances of Transforms async - /// The factory used to make a request synchronizationHelper - /// What is the we will use for telemetry - /// When creating a span for operations how noisy should the attributes be - /// throws You must provide at least one type of message mapper registry - public Dispatcher( - IAmACommandProcessor commandProcessor, - IEnumerable subscriptions, - IAmAMessageMapperRegistry? messageMapperRegistry = null, - IAmAMessageMapperRegistryAsync? messageMapperRegistryAsync = null, - IAmAMessageTransformerFactory? messageTransformerFactory = null, - IAmAMessageTransformerFactoryAsync? messageTransformerFactoryAsync= null, - IAmARequestContextFactory? requestContextFactory = null, - IAmABrighterTracer? tracer = null, - InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) - : this(() => - new CommandProcessorProvider(commandProcessor), subscriptions, messageMapperRegistry, - messageMapperRegistryAsync, messageTransformerFactory, messageTransformerFactoryAsync, - requestContextFactory, tracer, instrumentationOptions - ) - { - } - /// /// Stop listening to messages /// @@ -402,7 +366,7 @@ private Consumer CreateConsumer(Subscription subscription, int? consumerNumber) { var types = new[] { - typeof(IAmACommandProcessorProvider), typeof(Subscription), typeof(IAmAMessageMapperRegistry), + typeof(IAmACommandProcessor), typeof(Subscription), typeof(IAmAMessageMapperRegistry), typeof(IAmAMessageTransformerFactory), typeof(IAmARequestContextFactory), typeof(IAmABrighterTracer), typeof(InstrumentationOptions) }; @@ -414,7 +378,7 @@ private Consumer CreateConsumer(Subscription subscription, int? consumerNumber) var consumerFactory = (IConsumerFactory)consumerFactoryCtor?.Invoke(new object?[] { - CommandProcessorFactory.Invoke(), subscription, _messageMapperRegistry, _messageTransformerFactory, + CommandProcessor, subscription, _messageMapperRegistry, _messageTransformerFactory, _requestContextFactory, _tracer, _instrumentationOptions })!; @@ -425,7 +389,7 @@ private Consumer CreateConsumer(Subscription subscription, int? consumerNumber) { var types = new[] { - typeof(IAmACommandProcessorProvider),typeof(Subscription), typeof(IAmAMessageMapperRegistryAsync), + typeof(IAmACommandProcessor),typeof(Subscription), typeof(IAmAMessageMapperRegistryAsync), typeof(IAmAMessageTransformerFactoryAsync), typeof(IAmARequestContextFactory), typeof(IAmABrighterTracer), typeof(InstrumentationOptions) }; @@ -437,7 +401,7 @@ private Consumer CreateConsumer(Subscription subscription, int? consumerNumber) var consumerFactory = (IConsumerFactory)consumerFactoryCtor?.Invoke(new object?[] { - CommandProcessorFactory.Invoke(), subscription, _messageMapperRegistryAsync, _messageTransformerFactoryAsync, + CommandProcessor, subscription, _messageMapperRegistryAsync, _messageTransformerFactoryAsync, _requestContextFactory, _tracer, _instrumentationOptions })!; diff --git a/src/Paramore.Brighter.ServiceActivator/IAmACommandProcessorProvider.cs b/src/Paramore.Brighter.ServiceActivator/IAmACommandProcessorProvider.cs deleted file mode 100644 index a079bd5253..0000000000 --- a/src/Paramore.Brighter.ServiceActivator/IAmACommandProcessorProvider.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; - -namespace Paramore.Brighter.ServiceActivator -{ - public interface IAmACommandProcessorProvider : IDisposable - { - IAmACommandProcessor Get(); - - void CreateScope(); - - void ReleaseScope(); - } -} diff --git a/src/Paramore.Brighter.ServiceActivator/MessagePump.cs b/src/Paramore.Brighter.ServiceActivator/MessagePump.cs index 65dbe90a59..b5a9b7e1d7 100644 --- a/src/Paramore.Brighter.ServiceActivator/MessagePump.cs +++ b/src/Paramore.Brighter.ServiceActivator/MessagePump.cs @@ -23,14 +23,9 @@ THE SOFTWARE. */ #endregion using System; -using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Paramore.Brighter.Actions; using Paramore.Brighter.Logging; using Paramore.Brighter.Observability; -using Polly.CircuitBreaker; namespace Paramore.Brighter.ServiceActivator { @@ -52,7 +47,7 @@ public abstract class MessagePump where TRequest : class, IRequest { internal static readonly ILogger s_logger = ApplicationLogging.CreateLogger>(); - protected readonly IAmACommandProcessorProvider CommandProcessorProvider; + protected readonly IAmACommandProcessor CommandProcessor; protected readonly IAmARequestContextFactory RequestContextFactory; protected readonly IAmABrighterTracer? Tracer; protected readonly InstrumentationOptions InstrumentationOptions; @@ -101,18 +96,18 @@ public abstract class MessagePump where TRequest : class, IRequest /// - Dispatches the message to waiting handlers /// The message pump is a classic event loop and is intended to be run on a single-thread /// - /// Provides a correctly scoped command processor + /// Provides a correctly scoped command processor /// Provides a request synchronizationHelper /// What is the we will use for telemetry /// - /// When creating a span for operations how noisy should the attributes be + /// When creating a span for operations how noisy should the attributes be protected MessagePump( - IAmACommandProcessorProvider commandProcessorProvider, + IAmACommandProcessor commandProcessor, IAmARequestContextFactory requestContextFactory, IAmABrighterTracer? tracer, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) { - CommandProcessorProvider = commandProcessorProvider; + CommandProcessor = commandProcessor; RequestContextFactory = requestContextFactory; Tracer = tracer; InstrumentationOptions = instrumentationOptions; diff --git a/src/Paramore.Brighter.ServiceActivator/Proactor.cs b/src/Paramore.Brighter.ServiceActivator/Proactor.cs index 8d1446799c..bd4f2d15c9 100644 --- a/src/Paramore.Brighter.ServiceActivator/Proactor.cs +++ b/src/Paramore.Brighter.ServiceActivator/Proactor.cs @@ -46,7 +46,7 @@ public class Proactor : MessagePump, IAmAMessagePump where T /// /// Constructs a message pump /// - /// Provides a way to grab a command processor correctly scoped + /// Provides a way to grab a command processor correctly scoped /// The registry of mappers /// The factory that lets us create instances of transforms /// A factory to create instances of request synchronizationHelper, used to add synchronizationHelper to a pipeline @@ -54,14 +54,14 @@ public class Proactor : MessagePump, IAmAMessagePump where T /// What is the tracer we will use for telemetry /// When creating a span for operations how noisy should the attributes be public Proactor( - IAmACommandProcessorProvider commandProcessorProvider, + IAmACommandProcessor commandProcessor, IAmAMessageMapperRegistryAsync messageMapperRegistry, IAmAMessageTransformerFactoryAsync messageTransformerFactory, IAmARequestContextFactory requestContextFactory, IAmAChannelAsync channel, IAmABrighterTracer? tracer = null, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) - : base(commandProcessorProvider, requestContextFactory, tracer, instrumentationOptions) + : base(commandProcessor, requestContextFactory, tracer, instrumentationOptions) { var transformPipelineBuilder = new TransformPipelineBuilderAsync(messageMapperRegistry, messageTransformerFactory); _unwrapPipeline = transformPipelineBuilder.BuildUnwrapPipeline(); @@ -115,16 +115,14 @@ private async Task DispatchRequest(MessageHeader messageHeader, TRequest request { case MessageType.MT_COMMAND: { - await CommandProcessorProvider - .Get() + await CommandProcessor .SendAsync(request,requestContext, continueOnCapturedContext: true, default); break; } case MessageType.MT_DOCUMENT: case MessageType.MT_EVENT: { - await CommandProcessorProvider - .Get() + await CommandProcessor .PublishAsync(request, requestContext, continueOnCapturedContext: true, default); break; } @@ -221,8 +219,6 @@ private async Task EventLoop() var request = await TranslateMessage(message, context); - CommandProcessorProvider.CreateScope(); - await DispatchRequest(message.Header, request, context); span?.SetStatus(ActivityStatusCode.Ok); @@ -303,7 +299,6 @@ private async Task EventLoop() finally { Tracer?.EndSpan(span); - CommandProcessorProvider.ReleaseScope(); } await Acknowledge(message); diff --git a/src/Paramore.Brighter.ServiceActivator/Reactor.cs b/src/Paramore.Brighter.ServiceActivator/Reactor.cs index 2275b6c766..35366770b0 100644 --- a/src/Paramore.Brighter.ServiceActivator/Reactor.cs +++ b/src/Paramore.Brighter.ServiceActivator/Reactor.cs @@ -48,7 +48,7 @@ public class Reactor : MessagePump, IAmAMessagePump where TR /// /// Constructs a message pump /// - /// Provides a way to grab a command processor correctly scoped + /// Provides a way to grab a command processor correctly scoped /// The registry of mappers /// The factory that lets us create instances of transforms /// A factory to create instances of request synchronizationHelper, used to add synchronizationHelper to a pipeline @@ -56,14 +56,14 @@ public class Reactor : MessagePump, IAmAMessagePump where TR /// What is the tracer we will use for telemetry /// When creating a span for operations how noisy should the attributes be public Reactor( - IAmACommandProcessorProvider commandProcessorProvider, + IAmACommandProcessor commandProcessor, IAmAMessageMapperRegistry messageMapperRegistry, IAmAMessageTransformerFactory messageTransformerFactory, IAmARequestContextFactory requestContextFactory, IAmAChannelSync channel, IAmABrighterTracer? tracer = null, InstrumentationOptions instrumentationOptions = InstrumentationOptions.All) - : base(commandProcessorProvider, requestContextFactory, tracer, instrumentationOptions) + : base(commandProcessor, requestContextFactory, tracer, instrumentationOptions) { var transformPipelineBuilder = new TransformPipelineBuilder(messageMapperRegistry, messageTransformerFactory); _unwrapPipeline = transformPipelineBuilder.BuildUnwrapPipeline(); @@ -177,8 +177,6 @@ public void Run() var request = TranslateMessage(message, context); - CommandProcessorProvider.CreateScope(); - DispatchRequest(message.Header, request, context); span?.SetStatus(ActivityStatusCode.Ok); @@ -259,7 +257,6 @@ public void Run() finally { Tracer?.EndSpan(span); - CommandProcessorProvider.ReleaseScope(); } AcknowledgeMessage(message); @@ -295,13 +292,13 @@ private void DispatchRequest(MessageHeader messageHeader, TRequest request, Requ { case MessageType.MT_COMMAND: { - CommandProcessorProvider.Get().Send(request, requestContext); + CommandProcessor.Send(request, requestContext); break; } case MessageType.MT_DOCUMENT: case MessageType.MT_EVENT: { - CommandProcessorProvider.Get().Publish(request, requestContext); + CommandProcessor.Publish(request, requestContext); break; } } diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/When_throwing_defer_action_respect_redrive.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/When_throwing_defer_action_respect_redrive.cs index 76e4731a02..6572e26a60 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/When_throwing_defer_action_respect_redrive.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/When_throwing_defer_action_respect_redrive.cs @@ -98,7 +98,6 @@ public SnsReDrivePolicySDlqTests() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry() ); - var provider = new CommandProcessorProvider(commandProcessor); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyDeferredCommandMessageMapper()), @@ -107,7 +106,7 @@ public SnsReDrivePolicySDlqTests() messageMapperRegistry.Register(); //pump messages from a channel to a handler - in essence we are building our own dispatcher in this test - _messagePump = new Reactor(provider, messageMapperRegistry, + _messagePump = new Reactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 diff --git a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/When_throwing_defer_action_respect_redrive_async.cs b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/When_throwing_defer_action_respect_redrive_async.cs index f7445b49b7..e1505e3d47 100644 --- a/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/When_throwing_defer_action_respect_redrive_async.cs +++ b/tests/Paramore.Brighter.AWS.Tests/MessagingGateway/When_throwing_defer_action_respect_redrive_async.cs @@ -84,7 +84,6 @@ public SnsReDrivePolicySDlqTestsAsync() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry() ); - var provider = new CommandProcessorProvider(commandProcessor); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyDeferredCommandMessageMapper()), @@ -92,7 +91,7 @@ public SnsReDrivePolicySDlqTestsAsync() ); messageMapperRegistry.Register(); - _messagePump = new Proactor(provider, messageMapperRegistry, + _messagePump = new Proactor(commandProcessor, messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Call/When_Calling_A_Server_Via_The_Command_Processor.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Call/When_Calling_A_Server_Via_The_Command_Processor.cs index 147e17211b..4166e21b74 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Call/When_Calling_A_Server_Via_The_Command_Processor.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Call/When_Calling_A_Server_Via_The_Command_Processor.cs @@ -105,14 +105,12 @@ public CommandProcessorCallTests() public void When_Calling_A_Server_Via_The_Command_Processor() { //start a message pump on a new thread, to recieve the Call message - var provider = new CommandProcessorProvider(_commandProcessor); - Channel channel = new( new("MyChannel"), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, TimeProvider.System, TimeSpan.FromMilliseconds(1000)) ); - var messagePump = new Reactor(provider, _messageMapperRegistry, + var messagePump = new Reactor(_commandProcessor, _messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_channel_failure_exception_is_thrown_for_command_should_retry_until_connection_re_established_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_channel_failure_exception_is_thrown_for_command_should_retry_until_connection_re_established_async.cs index df2be8b895..8a40093064 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_channel_failure_exception_is_thrown_for_command_should_retry_until_connection_re_established_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_channel_failure_exception_is_thrown_for_command_should_retry_until_connection_re_established_async.cs @@ -46,7 +46,6 @@ public class MessagePumpRetryCommandOnConnectionFailureTestsAsync public MessagePumpRetryCommandOnConnectionFailureTestsAsync() { _commandProcessor = new SpyCommandProcessor(); - var provider = new CommandProcessorProvider(_commandProcessor); var channel = new FailingChannelAsync( new ChannelName(ChannelName), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000)), @@ -58,7 +57,7 @@ public MessagePumpRetryCommandOnConnectionFailureTestsAsync() null, new SimpleMessageMapperFactoryAsync(_ => new MyCommandMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - _messagePump = new Proactor(provider, messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel) + _messagePump = new Proactor(_commandProcessor, messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(500), RequeueCount = -1 }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_channel_failure_exception_is_thrown_for_event_should_retry_until_connection_re_established_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_channel_failure_exception_is_thrown_for_event_should_retry_until_connection_re_established_async.cs index dc8afe1a0e..404ac3342c 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_channel_failure_exception_is_thrown_for_event_should_retry_until_connection_re_established_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_channel_failure_exception_is_thrown_for_event_should_retry_until_connection_re_established_async.cs @@ -45,7 +45,6 @@ public class MessagePumpRetryEventConnectionFailureTestsAsync public MessagePumpRetryEventConnectionFailureTestsAsync() { _commandProcessor = new SpyCommandProcessor(); - var provider = new CommandProcessorProvider(_commandProcessor); var channel = new FailingChannelAsync( new ChannelName("myChannel"), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000)), @@ -59,7 +58,7 @@ public MessagePumpRetryEventConnectionFailureTestsAsync() new SimpleMessageMapperFactoryAsync(_ => new MyEventMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - _messagePump = new Proactor(provider, messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel) + _messagePump = new Proactor(_commandProcessor, messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(500), RequeueCount = -1 }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_command_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_command_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected_async.cs index e1cd10b1b6..783b397ea3 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_command_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_command_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected_async.cs @@ -46,7 +46,6 @@ public class MessagePumpCommandProcessingDeferMessageActionTestsAsync public MessagePumpCommandProcessingDeferMessageActionTestsAsync() { SpyRequeueCommandProcessor commandProcessor = new(); - var commandProcessorProvider = new CommandProcessorProvider(commandProcessor); _channel = new ChannelAsync(new(ChannelName),_routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000))); @@ -55,7 +54,7 @@ public MessagePumpCommandProcessingDeferMessageActionTestsAsync() new SimpleMessageMapperFactoryAsync(_ => new MyCommandMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - _messagePump = new Proactor(commandProcessorProvider, messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) + _messagePump = new Proactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = _requeueCount }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_command_handler_throws_unhandled_exception_Then_message_is_acked_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_command_handler_throws_unhandled_exception_Then_message_is_acked_async.cs index d498efb739..d3e1af3a84 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_command_handler_throws_unhandled_exception_Then_message_is_acked_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_command_handler_throws_unhandled_exception_Then_message_is_acked_async.cs @@ -46,7 +46,6 @@ public class MessagePumpCommandProcessingExceptionTestsAsync public MessagePumpCommandProcessingExceptionTestsAsync() { SpyExceptionCommandProcessor commandProcessor = new(); - var commandProcessorProvider = new CommandProcessorProvider(commandProcessor); InternalBus bus = new(); @@ -57,7 +56,7 @@ public MessagePumpCommandProcessingExceptionTestsAsync() new SimpleMessageMapperFactoryAsync(_ => new MyCommandMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - _messagePump = new Proactor(commandProcessorProvider, messageMapperRegistry, + _messagePump = new Proactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel ) { diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_fails_to_be_mapped_to_a_request_and_the_unacceptable_message_limit_is_reached_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_fails_to_be_mapped_to_a_request_and_the_unacceptable_message_limit_is_reached_async.cs index 1fa89c187e..9c73534117 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_fails_to_be_mapped_to_a_request_and_the_unacceptable_message_limit_is_reached_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_fails_to_be_mapped_to_a_request_and_the_unacceptable_message_limit_is_reached_async.cs @@ -42,7 +42,6 @@ public class MessagePumpUnacceptableMessageLimitTestsAsync public MessagePumpUnacceptableMessageLimitTestsAsync() { SpyRequeueCommandProcessor commandProcessor = new(); - var provider = new CommandProcessorProvider(commandProcessor); var channel = new ChannelAsync( new (Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000)), @@ -53,7 +52,7 @@ public MessagePumpUnacceptableMessageLimitTestsAsync() new SimpleMessageMapperFactoryAsync(_ => new FailingEventMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - _messagePump = new Proactor(provider, messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel) + _messagePump = new Proactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3, UnacceptableMessageLimit = 3 }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_fails_to_be_mapped_to_a_request_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_fails_to_be_mapped_to_a_request_async.cs index 902268e4dc..7733846869 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_fails_to_be_mapped_to_a_request_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_fails_to_be_mapped_to_a_request_async.cs @@ -20,7 +20,6 @@ public class MessagePumpFailingMessageTranslationTestsAsync public MessagePumpFailingMessageTranslationTestsAsync() { SpyRequeueCommandProcessor commandProcessor = new(); - var provider = new CommandProcessorProvider(commandProcessor); _channel = new ChannelAsync( new(ChannelName), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000)) @@ -30,7 +29,7 @@ public MessagePumpFailingMessageTranslationTestsAsync() new SimpleMessageMapperFactoryAsync(_ => new FailingEventMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - _messagePump = new Proactor(provider, messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) + _messagePump = new Proactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3, UnacceptableMessageLimit = 3 }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_is_dispatched_it_should_reach_a_handler_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_is_dispatched_it_should_reach_a_handler_async.cs index 03249b7577..cde83ff4d2 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_is_dispatched_it_should_reach_a_handler_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_message_is_dispatched_it_should_reach_a_handler_async.cs @@ -29,8 +29,6 @@ public MessagePumpDispatchAsyncTests() handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry()); - - var commandProcessorProvider = new CommandProcessorProvider(commandProcessor); PipelineBuilder.ClearPipelineCache(); @@ -40,7 +38,7 @@ public MessagePumpDispatchAsyncTests() new SimpleMessageMapperFactoryAsync(_ => new MyEventMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - _messagePump = new Proactor(commandProcessorProvider, messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel) + _messagePump = new Proactor(commandProcessor, messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; var message = new Message(new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_EVENT), new MessageBody(JsonSerializer.Serialize(_myEvent))); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_count_threshold_for_commands_has_been_reached.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_count_threshold_for_commands_has_been_reached.cs index a8ecafeaa4..0ec97dc07a 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_count_threshold_for_commands_has_been_reached.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_count_threshold_for_commands_has_been_reached.cs @@ -47,7 +47,6 @@ public class MessagePumpCommandRequeueCountThresholdTestsAsync public MessagePumpCommandRequeueCountThresholdTestsAsync() { _commandProcessor = new SpyRequeueCommandProcessor(); - var provider = new CommandProcessorProvider(_commandProcessor); _channel = new ChannelAsync(new(Channel) ,_routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000))); var messageMapperRegistry = new MessageMapperRegistry( @@ -55,7 +54,7 @@ public MessagePumpCommandRequeueCountThresholdTestsAsync() new SimpleMessageMapperFactoryAsync(_ => new MyCommandMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - _messagePump = new Proactor(provider, messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel) + _messagePump = new Proactor(_commandProcessor, messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 }; var message1 = new Message(new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_count_threshold_for_events_has_been_reached.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_count_threshold_for_events_has_been_reached.cs index fb8c6f2033..08eea28867 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_count_threshold_for_events_has_been_reached.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_count_threshold_for_events_has_been_reached.cs @@ -47,7 +47,6 @@ public class MessagePumpEventRequeueCountThresholdTestsAsync public MessagePumpEventRequeueCountThresholdTestsAsync() { _commandProcessor = new SpyRequeueCommandProcessor(); - var provider = new CommandProcessorProvider(_commandProcessor); _channel = new ChannelAsync(new(Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000))); var messageMapperRegistry = new MessageMapperRegistry( @@ -55,7 +54,7 @@ public MessagePumpEventRequeueCountThresholdTestsAsync() new SimpleMessageMapperFactoryAsync(_ => new MyEventMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - _messagePump = new Proactor(provider, messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel) + _messagePump = new Proactor(_commandProcessor, messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 }; var message1 = new Message( diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_of_command_exception_is_thrown.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_of_command_exception_is_thrown.cs index 791a905ae6..8b7d895212 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_of_command_exception_is_thrown.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_of_command_exception_is_thrown.cs @@ -47,7 +47,6 @@ public class MessagePumpCommandRequeueTestsAsync public MessagePumpCommandRequeueTestsAsync() { _commandProcessor = new SpyRequeueCommandProcessor(); - var provider = new CommandProcessorProvider(_commandProcessor); ChannelAsync channel = new(new(Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000)), 2); var messageMapperRegistry = new MessageMapperRegistry( @@ -55,7 +54,7 @@ public MessagePumpCommandRequeueTestsAsync() new SimpleMessageMapperFactoryAsync(_ => new MyCommandMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - _messagePump = new Proactor(provider, messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel) + _messagePump = new Proactor(_commandProcessor, messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = -1 }; var message1 = new Message( diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_of_event_exception_is_thrown.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_of_event_exception_is_thrown.cs index 7f61bc0ecc..50f775a462 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_of_event_exception_is_thrown.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_a_requeue_of_event_exception_is_thrown.cs @@ -46,7 +46,6 @@ public class MessagePumpEventRequeueTestsAsync public MessagePumpEventRequeueTestsAsync() { _commandProcessor = new SpyRequeueCommandProcessor(); - var provider = new CommandProcessorProvider(_commandProcessor); ChannelAsync channel = new( new(Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000)), @@ -58,7 +57,7 @@ public MessagePumpEventRequeueTestsAsync() new SimpleMessageMapperFactoryAsync(_ => new MyEventMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - _messagePump = new Proactor(provider, messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel) + _messagePump = new Proactor(_commandProcessor, messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = -1 }; var message1 = new Message( diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_event_handler_throws_a_defer_message_Then_message_is_requeued_until_rejectedAsync.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_event_handler_throws_a_defer_message_Then_message_is_requeued_until_rejectedAsync.cs index 5145e08882..ef6f6e94fe 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_event_handler_throws_a_defer_message_Then_message_is_requeued_until_rejectedAsync.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_event_handler_throws_a_defer_message_Then_message_is_requeued_until_rejectedAsync.cs @@ -46,7 +46,6 @@ public class MessagePumpEventProcessingDeferMessageActionTestsAsync public MessagePumpEventProcessingDeferMessageActionTestsAsync() { SpyRequeueCommandProcessor commandProcessor = new(); - var commandProcessorProvider = new CommandProcessorProvider(commandProcessor); _bus = new InternalBus(); _channel = new ChannelAsync(new (Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000))); @@ -56,7 +55,7 @@ public MessagePumpEventProcessingDeferMessageActionTestsAsync() new SimpleMessageMapperFactoryAsync(_ => new MyEventMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - _messagePump = new Proactor(commandProcessorProvider, messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel) + _messagePump = new Proactor(commandProcessor, messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = _requeueCount }; var msg = new TransformPipelineBuilderAsync(messageMapperRegistry, null) diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_event_handler_throws_unhandled_exception_Then_message_is_acked_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_event_handler_throws_unhandled_exception_Then_message_is_acked_async.cs index 591b8766d5..e1b05b6200 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_event_handler_throws_unhandled_exception_Then_message_is_acked_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_event_handler_throws_unhandled_exception_Then_message_is_acked_async.cs @@ -48,7 +48,6 @@ public class MessagePumpEventProcessingExceptionTestsAsync public MessagePumpEventProcessingExceptionTestsAsync() { SpyExceptionCommandProcessor commandProcessor = new(); - var commandProcessorProvider = new CommandProcessorProvider(commandProcessor); var bus = new InternalBus(); @@ -59,7 +58,7 @@ public MessagePumpEventProcessingExceptionTestsAsync() new SimpleMessageMapperFactoryAsync(_ => new MyEventMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - _messagePump = new Proactor(commandProcessorProvider, messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) + _messagePump = new Proactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = _requeueCount }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_is_recieved_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_is_recieved_async.cs index e18490fd86..efc4d16e27 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_is_recieved_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_is_recieved_async.cs @@ -45,7 +45,6 @@ public class AsyncMessagePumpUnacceptableMessageTests public AsyncMessagePumpUnacceptableMessageTests() { SpyRequeueCommandProcessor commandProcessor = new(); - var provider = new CommandProcessorProvider(commandProcessor); _bus = new InternalBus(); @@ -59,7 +58,7 @@ public AsyncMessagePumpUnacceptableMessageTests() new SimpleMessageMapperFactoryAsync(_ => new MyEventMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - _messagePump = new Proactor(provider, messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) + _messagePump = new Proactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_limit_is_reached_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_limit_is_reached_async.cs index fd7a5a9a86..b02da39874 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_limit_is_reached_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_an_unacceptable_message_limit_is_reached_async.cs @@ -42,7 +42,6 @@ public class MessagePumpUnacceptableMessageLimitBreachedAsyncTests public MessagePumpUnacceptableMessageLimitBreachedAsyncTests() { SpyRequeueCommandProcessor commandProcessor = new(); - var provider = new CommandProcessorProvider(commandProcessor); var channel = new ChannelAsync(new("MyChannel"), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000)), 3); @@ -51,7 +50,7 @@ public MessagePumpUnacceptableMessageLimitBreachedAsyncTests() new SimpleMessageMapperFactoryAsync(_ => new MyEventMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - _messagePump = new Proactor(provider, messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel) + _messagePump = new Proactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3, UnacceptableMessageLimit = 3 }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_reading_a_message_from_a_channel_pump_out_to_command_processor_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_reading_a_message_from_a_channel_pump_out_to_command_processor_async.cs index a95753f876..2f39d3dfd2 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_reading_a_message_from_a_channel_pump_out_to_command_processor_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_reading_a_message_from_a_channel_pump_out_to_command_processor_async.cs @@ -46,7 +46,6 @@ public class MessagePumpToCommandProcessorTestsAsync public MessagePumpToCommandProcessorTestsAsync() { _commandProcessor = new SpyCommandProcessor(); - var provider = new CommandProcessorProvider(_commandProcessor); ChannelAsync channel = new( new(Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000)) @@ -56,7 +55,7 @@ public MessagePumpToCommandProcessorTestsAsync() new SimpleMessageMapperFactoryAsync(_ => new MyEventMessageMapperAsync())); messagerMapperRegistry.RegisterAsync(); - _messagePump = new Proactor(provider, messagerMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel) + _messagePump = new Proactor(_commandProcessor, messagerMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; _event = new MyEvent(); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_running_a_message_pump_on_a_thread_should_be_able_to_stop_async.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_running_a_message_pump_on_a_thread_should_be_able_to_stop_async.cs index 5524cab749..faeb7bce22 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_running_a_message_pump_on_a_thread_should_be_able_to_stop_async.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Proactor/When_running_a_message_pump_on_a_thread_should_be_able_to_stop_async.cs @@ -45,7 +45,6 @@ public class PerformerCanStopTestsAsync public PerformerCanStopTestsAsync() { SpyCommandProcessor commandProcessor = new(); - var provider = new CommandProcessorProvider(commandProcessor); ChannelAsync channel = new( new(Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000)) @@ -56,7 +55,7 @@ public PerformerCanStopTestsAsync() new SimpleMessageMapperFactoryAsync(_ => new MyEventMessageMapperAsync())); messageMapperRegistry.RegisterAsync(); - var messagePump = new Proactor(provider, messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel); + var messagePump = new Proactor(commandProcessor, messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), channel); messagePump.Channel = channel; messagePump.TimeOut = TimeSpan.FromMilliseconds(5000); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_channel_failure_exception_is_thrown_for_command_should_retry_until_connection_re_established.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_channel_failure_exception_is_thrown_for_command_should_retry_until_connection_re_established.cs index 6461926068..d1073871ba 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_channel_failure_exception_is_thrown_for_command_should_retry_until_connection_re_established.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_channel_failure_exception_is_thrown_for_command_should_retry_until_connection_re_established.cs @@ -46,7 +46,6 @@ public class MessagePumpRetryCommandOnConnectionFailureTests public MessagePumpRetryCommandOnConnectionFailureTests() { _commandProcessor = new SpyCommandProcessor(); - var provider = new CommandProcessorProvider(_commandProcessor); var channel = new FailingChannel( new ChannelName(ChannelName), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000)), @@ -58,7 +57,7 @@ public MessagePumpRetryCommandOnConnectionFailureTests() new SimpleMessageMapperFactory(_ => new MyCommandMessageMapper()), null); messageMapperRegistry.Register(); - _messagePump = new Reactor(provider, messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel) + _messagePump = new Reactor(_commandProcessor, messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(500), RequeueCount = -1 }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_channel_failure_exception_is_thrown_for_event_should_retry_until_connection_re_established.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_channel_failure_exception_is_thrown_for_event_should_retry_until_connection_re_established.cs index 2b644fc56e..4b610a8adb 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_channel_failure_exception_is_thrown_for_event_should_retry_until_connection_re_established.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_channel_failure_exception_is_thrown_for_event_should_retry_until_connection_re_established.cs @@ -45,7 +45,6 @@ public class MessagePumpRetryEventConnectionFailureTests public MessagePumpRetryEventConnectionFailureTests() { _commandProcessor = new SpyCommandProcessor(); - var provider = new CommandProcessorProvider(_commandProcessor); var channel = new FailingChannel( new ChannelName("myChannel"), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000)), @@ -59,7 +58,7 @@ public MessagePumpRetryEventConnectionFailureTests() null); messageMapperRegistry.Register(); - _messagePump = new Reactor(provider, messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel) + _messagePump = new Reactor(_commandProcessor, messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(500), RequeueCount = -1 }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_command_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_command_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected.cs index f37d603fb4..15c9bef078 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_command_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_command_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected.cs @@ -44,7 +44,6 @@ public class MessagePumpCommandProcessingDeferMessageActionTests public MessagePumpCommandProcessingDeferMessageActionTests() { SpyRequeueCommandProcessor commandProcessor = new(); - var provider = new CommandProcessorProvider(commandProcessor); _channel = new Channel(new("myChannel"), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000))); @@ -53,7 +52,7 @@ public MessagePumpCommandProcessingDeferMessageActionTests() null); messageMapperRegistry.Register(); - _messagePump = new Reactor(provider, messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) + _messagePump = new Reactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = _requeueCount }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_command_handler_throws_unhandled_exception_Then_message_is_acked.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_command_handler_throws_unhandled_exception_Then_message_is_acked.cs index 661428fea6..eadb9cbeb4 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_command_handler_throws_unhandled_exception_Then_message_is_acked.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_command_handler_throws_unhandled_exception_Then_message_is_acked.cs @@ -46,7 +46,6 @@ public class MessagePumpCommandProcessingExceptionTests public MessagePumpCommandProcessingExceptionTests() { SpyExceptionCommandProcessor commandProcessor = new(); - var provider = new CommandProcessorProvider(commandProcessor); InternalBus bus = new(); _channel = new Channel(new("myChannel"),_routingKey, new InMemoryMessageConsumer(_routingKey, bus, _timeProvider, TimeSpan.FromMilliseconds(1000))); @@ -56,7 +55,7 @@ public MessagePumpCommandProcessingExceptionTests() null); messageMapperRegistry.Register(); - _messagePump = new Reactor(provider, messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) + _messagePump = new Reactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = _requeueCount }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_fails_to_be_mapped_to_a_request.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_fails_to_be_mapped_to_a_request.cs index 54830f05c2..dd22bf84a3 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_fails_to_be_mapped_to_a_request.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_fails_to_be_mapped_to_a_request.cs @@ -20,7 +20,6 @@ public class MessagePumpFailingMessageTranslationTests public MessagePumpFailingMessageTranslationTests() { SpyRequeueCommandProcessor commandProcessor = new(); - var provider = new CommandProcessorProvider(commandProcessor); _channel = new Channel(new(Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000))); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new FailingEventMessageMapper()), @@ -28,7 +27,7 @@ public MessagePumpFailingMessageTranslationTests() messageMapperRegistry.Register(); var messageTransformerFactory = new SimpleMessageTransformerFactory(_ => throw new NotImplementedException()); - _messagePump = new Reactor(provider, messageMapperRegistry, messageTransformerFactory, new InMemoryRequestContextFactory(), _channel) + _messagePump = new Reactor(commandProcessor, messageMapperRegistry, messageTransformerFactory, new InMemoryRequestContextFactory(), _channel) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3, UnacceptableMessageLimit = 3 }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_fails_to_be_mapped_to_a_request_and_the_unacceptable_message_limit_is_reached.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_fails_to_be_mapped_to_a_request_and_the_unacceptable_message_limit_is_reached.cs index 9bfe7442c4..b0bfb0b3fc 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_fails_to_be_mapped_to_a_request_and_the_unacceptable_message_limit_is_reached.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_fails_to_be_mapped_to_a_request_and_the_unacceptable_message_limit_is_reached.cs @@ -42,7 +42,6 @@ public class MessagePumpUnacceptableMessageLimitTests public MessagePumpUnacceptableMessageLimitTests() { SpyRequeueCommandProcessor commandProcessor = new(); - var provider = new CommandProcessorProvider(commandProcessor); _timeProvider = new FakeTimeProvider(); Channel channel = new(new (Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000))); var messageMapperRegistry = new MessageMapperRegistry( @@ -50,7 +49,7 @@ public MessagePumpUnacceptableMessageLimitTests() null); messageMapperRegistry.Register(); - _messagePump = new Reactor(provider, messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel) + _messagePump = new Reactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3, UnacceptableMessageLimit = 3 }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_is_dispatched_it_should_reach_a_handler.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_is_dispatched_it_should_reach_a_handler.cs index 87d7298c4b..8fd3e3b18f 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_is_dispatched_it_should_reach_a_handler.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_message_is_dispatched_it_should_reach_a_handler.cs @@ -55,8 +55,6 @@ public MessagePumpDispatchTests() handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry()); - - var provider = new CommandProcessorProvider(commandProcessor); PipelineBuilder.ClearPipelineCache(); @@ -70,7 +68,7 @@ public MessagePumpDispatchTests() null); messageMapperRegistry.Register(); - _messagePump = new Reactor(provider, messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel) + _messagePump = new Reactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_count_threshold_for_commands_has_been_reached.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_count_threshold_for_commands_has_been_reached.cs index 3e12ed4e1e..7fae434430 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_count_threshold_for_commands_has_been_reached.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_count_threshold_for_commands_has_been_reached.cs @@ -47,13 +47,12 @@ public class MessagePumpCommandRequeueCountThresholdTests public MessagePumpCommandRequeueCountThresholdTests() { _commandProcessor = new SpyRequeueCommandProcessor(); - var provider = new CommandProcessorProvider(_commandProcessor); _channel = new Channel(new(Channel) ,_routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000))); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyCommandMessageMapper()), null); messageMapperRegistry.Register(); - _messagePump = new Reactor(provider, messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel) + _messagePump = new Reactor(_commandProcessor, messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 }; var message1 = new Message(new MessageHeader(Guid.NewGuid().ToString(), _routingKey, MessageType.MT_COMMAND), diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_count_threshold_for_events_has_been_reached.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_count_threshold_for_events_has_been_reached.cs index 900205faed..7aebe6dde2 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_count_threshold_for_events_has_been_reached.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_count_threshold_for_events_has_been_reached.cs @@ -47,14 +47,13 @@ public class MessagePumpEventRequeueCountThresholdTests public MessagePumpEventRequeueCountThresholdTests() { _commandProcessor = new SpyRequeueCommandProcessor(); - var provider = new CommandProcessorProvider(_commandProcessor); _channel = new Channel(new(Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000))); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyEventMessageMapper()), null); messageMapperRegistry.Register(); - _messagePump = new Reactor(provider, messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel) + _messagePump = new Reactor(_commandProcessor, messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 }; var message1 = new Message( diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_of_command_exception_is_thrown.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_of_command_exception_is_thrown.cs index cac2921f7b..dd8e4e3786 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_of_command_exception_is_thrown.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_of_command_exception_is_thrown.cs @@ -47,13 +47,12 @@ public class MessagePumpCommandRequeueTests public MessagePumpCommandRequeueTests() { _commandProcessor = new SpyRequeueCommandProcessor(); - var provider = new CommandProcessorProvider(_commandProcessor); Channel channel = new(new(Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000)), 2); var messageMapperRegistry = new MessageMapperRegistry( new SimpleMessageMapperFactory(_ => new MyCommandMessageMapper()), null); messageMapperRegistry.Register(); - _messagePump = new Reactor(provider, messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel) + _messagePump = new Reactor(_commandProcessor, messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = -1 }; var message1 = new Message( diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_of_event_exception_is_thrown.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_of_event_exception_is_thrown.cs index d656dec013..b2af49decf 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_of_event_exception_is_thrown.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_a_requeue_of_event_exception_is_thrown.cs @@ -46,7 +46,6 @@ public class MessagePumpEventRequeueTests public MessagePumpEventRequeueTests() { _commandProcessor = new SpyRequeueCommandProcessor(); - var provider = new CommandProcessorProvider(_commandProcessor); Channel channel = new( new(Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000)), @@ -57,7 +56,7 @@ public MessagePumpEventRequeueTests() null); messageMapperRegistry.Register(); - _messagePump = new Reactor(provider, messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel) + _messagePump = new Reactor(_commandProcessor, messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = -1 }; var message1 = new Message( diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_event_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_event_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected.cs index 866f8c204f..31f1a88a38 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_event_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_event_handler_throws_a_defer_message_Then_message_is_requeued_until_rejected.cs @@ -48,7 +48,6 @@ public MessagePumpEventProcessingDeferMessageActionTests() _routingKey = new RoutingKey(Topic); SpyRequeueCommandProcessor commandProcessor = new(); - var provider = new CommandProcessorProvider(commandProcessor); _bus = new InternalBus(); @@ -62,7 +61,7 @@ public MessagePumpEventProcessingDeferMessageActionTests() null); messageMapperRegistry.Register(); - _messagePump = new Reactor(provider, messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) + _messagePump = new Reactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = _requeueCount }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_event_handler_throws_unhandled_exception_Then_message_is_acked.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_event_handler_throws_unhandled_exception_Then_message_is_acked.cs index 44c64fce44..6c2e6f9514 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_event_handler_throws_unhandled_exception_Then_message_is_acked.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_event_handler_throws_unhandled_exception_Then_message_is_acked.cs @@ -49,7 +49,6 @@ public class MessagePumpEventProcessingExceptionTests public MessagePumpEventProcessingExceptionTests() { SpyExceptionCommandProcessor commandProcessor = new(); - var provider = new CommandProcessorProvider(commandProcessor); _bus = new InternalBus(); @@ -63,7 +62,7 @@ public MessagePumpEventProcessingExceptionTests() messageMapperRegistry.Register(); var requestContextFactory = new InMemoryRequestContextFactory(); - _messagePump = new Reactor(provider, messageMapperRegistry, null, requestContextFactory, _channel) + _messagePump = new Reactor(commandProcessor, messageMapperRegistry, null, requestContextFactory, _channel) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = _requeueCount }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_is_recieved.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_is_recieved.cs index 340a4b15da..83eec53b6a 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_is_recieved.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_is_recieved.cs @@ -45,7 +45,6 @@ public class MessagePumpUnacceptableMessageTests public MessagePumpUnacceptableMessageTests() { SpyRequeueCommandProcessor commandProcessor = new(); - var provider = new CommandProcessorProvider(commandProcessor); _bus = new InternalBus(); @@ -56,7 +55,7 @@ public MessagePumpUnacceptableMessageTests() null); messageMapperRegistry.Register(); - _messagePump = new Reactor(provider, messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) + _messagePump = new Reactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_limit_is_reached.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_limit_is_reached.cs index 413f22b4b2..b0e50252a0 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_limit_is_reached.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_an_unacceptable_message_limit_is_reached.cs @@ -44,7 +44,6 @@ public class MessagePumpUnacceptableMessageLimitBreachedTests public MessagePumpUnacceptableMessageLimitBreachedTests() { SpyRequeueCommandProcessor commandProcessor = new(); - var provider = new CommandProcessorProvider(commandProcessor); _bus = new InternalBus(); @@ -54,7 +53,7 @@ public MessagePumpUnacceptableMessageLimitBreachedTests() null); messageMapperRegistry.Register(); - _messagePump = new Reactor(provider, messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel) + _messagePump = new Reactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3, UnacceptableMessageLimit = 3 }; diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_reading_a_message_from_a_channel_pump_out_to_command_processor.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_reading_a_message_from_a_channel_pump_out_to_command_processor.cs index ead38bff40..4377bd18ad 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_reading_a_message_from_a_channel_pump_out_to_command_processor.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_reading_a_message_from_a_channel_pump_out_to_command_processor.cs @@ -46,7 +46,6 @@ public class MessagePumpToCommandProcessorTests public MessagePumpToCommandProcessorTests() { _commandProcessor = new SpyCommandProcessor(); - var provider = new CommandProcessorProvider(_commandProcessor); Channel channel = new( new(Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000)) @@ -57,7 +56,7 @@ public MessagePumpToCommandProcessorTests() null); messagerMapperRegistry.Register(); - _messagePump = new Reactor(provider, messagerMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel) + _messagePump = new Reactor(_commandProcessor, messagerMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000) }; _event = new MyEvent(); diff --git a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_running_a_message_pump_on_a_thread_should_be_able_to_stop.cs b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_running_a_message_pump_on_a_thread_should_be_able_to_stop.cs index 10b6d501a7..5513f2f78d 100644 --- a/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_running_a_message_pump_on_a_thread_should_be_able_to_stop.cs +++ b/tests/Paramore.Brighter.Core.Tests/MessageDispatch/Reactor/When_running_a_message_pump_on_a_thread_should_be_able_to_stop.cs @@ -46,7 +46,6 @@ public class PerformerCanStopTests public PerformerCanStopTests() { SpyCommandProcessor commandProcessor = new(); - var provider = new CommandProcessorProvider(commandProcessor); Channel channel = new( new(Channel), _routingKey, new InMemoryMessageConsumer(_routingKey, _bus, _timeProvider, TimeSpan.FromMilliseconds(1000)) @@ -57,7 +56,7 @@ public PerformerCanStopTests() null); messageMapperRegistry.Register(); - var messagePump = new Reactor(provider, messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel); + var messagePump = new Reactor(commandProcessor, messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), channel); messagePump.Channel = channel; messagePump.TimeOut = TimeSpan.FromMilliseconds(5000); diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_Is_Dispatched_It_Should_Begin_A_Span.cs b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_Is_Dispatched_It_Should_Begin_A_Span.cs index b49f7c0e9c..aee0506f71 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_Is_Dispatched_It_Should_Begin_A_Span.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_A_Message_Is_Dispatched_It_Should_Begin_A_Span.cs @@ -82,8 +82,6 @@ public MessagePumpDispatchObservabilityTests() new PolicyRegistry(), tracer: tracer, instrumentationOptions: instrumentationOptions); - - var provider = new CommandProcessorProvider(commandProcessor); PipelineBuilder.ClearPipelineCache(); @@ -98,7 +96,7 @@ public MessagePumpDispatchObservabilityTests() null); messageMapperRegistry.Register(); - _messagePump = new Reactor(provider, messageMapperRegistry, null, + _messagePump = new Reactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel, tracer, instrumentationOptions) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000) diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Are_No_Messages_Close_The_Span.cs b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Are_No_Messages_Close_The_Span.cs index 1ee8c4017d..5d50cd3191 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Are_No_Messages_Close_The_Span.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Are_No_Messages_Close_The_Span.cs @@ -57,8 +57,6 @@ public MessagePumpEmptyQueueOberservabilityTests() new PolicyRegistry(), tracer: tracer, instrumentationOptions: instrumentationOptions); - - var provider = new CommandProcessorProvider(commandProcessor); PipelineBuilder.ClearPipelineCache(); @@ -69,7 +67,7 @@ public MessagePumpEmptyQueueOberservabilityTests() null); messageMapperRegistry.Register(); - _messagePump = new Reactor(provider, messageMapperRegistry, null, + _messagePump = new Reactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel, tracer, instrumentationOptions) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), EmptyChannelDelay = TimeSpan.FromMilliseconds(1000) diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_BrokenCircuit_Channel_Failure_Close_The_Span.cs b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_BrokenCircuit_Channel_Failure_Close_The_Span.cs index f2b876b87b..07c6642650 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_BrokenCircuit_Channel_Failure_Close_The_Span.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_BrokenCircuit_Channel_Failure_Close_The_Span.cs @@ -59,8 +59,6 @@ public MessagePumpBrokenCircuitChannelFailureOberservabilityTests() new PolicyRegistry(), tracer: tracer, instrumentationOptions: instrumentationOptions); - - var provider = new CommandProcessorProvider(commandProcessor); PipelineBuilder.ClearPipelineCache(); @@ -76,7 +74,7 @@ public MessagePumpBrokenCircuitChannelFailureOberservabilityTests() null); messageMapperRegistry.Register(); - _messagePump = new Reactor(provider, messageMapperRegistry, null, + _messagePump = new Reactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel, tracer, instrumentationOptions) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), EmptyChannelDelay = TimeSpan.FromMilliseconds(1000) diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_Channel_Failure_Close_The_Span.cs b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_Channel_Failure_Close_The_Span.cs index 88255ad2c1..80abbbefec 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_Channel_Failure_Close_The_Span.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_Channel_Failure_Close_The_Span.cs @@ -59,8 +59,6 @@ public MessagePumpChannelFailureOberservabilityTests() new PolicyRegistry(), tracer: tracer, instrumentationOptions: instrumentationOptions); - - var provider = new CommandProcessorProvider(commandProcessor); PipelineBuilder.ClearPipelineCache(); @@ -75,7 +73,7 @@ public MessagePumpChannelFailureOberservabilityTests() null); messageMapperRegistry.Register(); - _messagePump = new Reactor(provider, messageMapperRegistry, null, + _messagePump = new Reactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel, tracer, instrumentationOptions) { Channel = channel, TimeOut = TimeSpan.FromMilliseconds(5000), EmptyChannelDelay = TimeSpan.FromMilliseconds(1000) diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_Quit_Message_Close_The_Span.cs b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_Quit_Message_Close_The_Span.cs index c2988303ac..c091cf09c3 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_Quit_Message_Close_The_Span.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_A_Quit_Message_Close_The_Span.cs @@ -56,8 +56,6 @@ public MessagePumpQuitOberservabilityTests() new PolicyRegistry(), tracer: tracer, instrumentationOptions: instrumentationOptions); - - var provider = new CommandProcessorProvider(commandProcessor); PipelineBuilder.ClearPipelineCache(); @@ -71,7 +69,7 @@ public MessagePumpQuitOberservabilityTests() null); messageMapperRegistry.Register(); - _messagePump = new Reactor(provider, messageMapperRegistry, null, + _messagePump = new Reactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), channel, tracer, instrumentationOptions) { Channel = channel, TimeOut= TimeSpan.FromMilliseconds(5000), EmptyChannelDelay = TimeSpan.FromMilliseconds(1000) diff --git a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_An_Unacceptable_Messages_Close_The_Span.cs b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_An_Unacceptable_Messages_Close_The_Span.cs index 4ab4f13795..47d2334022 100644 --- a/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_An_Unacceptable_Messages_Close_The_Span.cs +++ b/tests/Paramore.Brighter.Core.Tests/Observability/MessageDispatch/When_There_Is_An_Unacceptable_Messages_Close_The_Span.cs @@ -58,8 +58,6 @@ public MessagePumpUnacceptableMessageOberservabilityTests() new PolicyRegistry(), tracer: tracer, instrumentationOptions: instrumentationOptions); - - var provider = new CommandProcessorProvider(commandProcessor); PipelineBuilder.ClearPipelineCache(); @@ -70,7 +68,7 @@ public MessagePumpUnacceptableMessageOberservabilityTests() null); messageMapperRegistry.Register(); - _messagePump = new Reactor(provider, messageMapperRegistry, null, + _messagePump = new Reactor(commandProcessor, messageMapperRegistry, null, new InMemoryRequestContextFactory(), _channel, tracer, instrumentationOptions) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), EmptyChannelDelay = TimeSpan.FromMilliseconds(1000) diff --git a/tests/Paramore.Brighter.RMQ.Tests/MessageDispatch/When_building_a_dispatcher.cs b/tests/Paramore.Brighter.RMQ.Tests/MessageDispatch/When_building_a_dispatcher.cs index 44d25c32e2..17a947532d 100644 --- a/tests/Paramore.Brighter.RMQ.Tests/MessageDispatch/When_building_a_dispatcher.cs +++ b/tests/Paramore.Brighter.RMQ.Tests/MessageDispatch/When_building_a_dispatcher.cs @@ -65,8 +65,7 @@ public DispatchBuilderTests() .Build(); _builder = DispatchBuilder.StartNew() - .CommandProcessorFactory(() => - new CommandProcessorProvider(commandProcessor), + .CommandProcessor(commandProcessor, new InMemoryRequestContextFactory() ) .MessageMappers(messageMapperRegistry, null, null, null) diff --git a/tests/Paramore.Brighter.RMQ.Tests/MessageDispatch/When_building_a_dispatcher_async.cs b/tests/Paramore.Brighter.RMQ.Tests/MessageDispatch/When_building_a_dispatcher_async.cs index c4d9be10db..9ab6f5682e 100644 --- a/tests/Paramore.Brighter.RMQ.Tests/MessageDispatch/When_building_a_dispatcher_async.cs +++ b/tests/Paramore.Brighter.RMQ.Tests/MessageDispatch/When_building_a_dispatcher_async.cs @@ -65,8 +65,7 @@ public DispatchBuilderTestsAsync() .Build(); _builder = DispatchBuilder.StartNew() - .CommandProcessorFactory(() => - new CommandProcessorProvider(commandProcessor), + .CommandProcessor(commandProcessor, new InMemoryRequestContextFactory() ) .MessageMappers(null, messageMapperRegistry, null, new EmptyMessageTransformerFactoryAsync()) diff --git a/tests/Paramore.Brighter.RMQ.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway.cs b/tests/Paramore.Brighter.RMQ.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway.cs index 53d38f26e9..80c2398ca9 100644 --- a/tests/Paramore.Brighter.RMQ.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway.cs +++ b/tests/Paramore.Brighter.RMQ.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway.cs @@ -60,8 +60,7 @@ public DispatchBuilderWithNamedGateway() .Build(); _builder = DispatchBuilder.StartNew() - .CommandProcessorFactory(() => - new CommandProcessorProvider(commandProcessor), + .CommandProcessor(commandProcessor, new InMemoryRequestContextFactory() ) .MessageMappers(messageMapperRegistry, null, new EmptyMessageTransformerFactory(), null) diff --git a/tests/Paramore.Brighter.RMQ.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway_async.cs b/tests/Paramore.Brighter.RMQ.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway_async.cs index 6f981df2dc..87125640be 100644 --- a/tests/Paramore.Brighter.RMQ.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway_async.cs +++ b/tests/Paramore.Brighter.RMQ.Tests/MessageDispatch/When_building_a_dispatcher_with_named_gateway_async.cs @@ -61,8 +61,7 @@ public DispatchBuilderWithNamedGatewayAsync() .Build(); _builder = DispatchBuilder.StartNew() - .CommandProcessorFactory(() => - new CommandProcessorProvider(commandProcessor), + .CommandProcessor(commandProcessor, new InMemoryRequestContextFactory() ) .MessageMappers(messageMapperRegistry, null, null, null) diff --git a/tests/Paramore.Brighter.RMQ.Tests/MessagingGateway/When_retry_limits_force_a_message_onto_the_DLQ.cs b/tests/Paramore.Brighter.RMQ.Tests/MessagingGateway/When_retry_limits_force_a_message_onto_the_DLQ.cs index cdf673f1d1..fd3f930465 100644 --- a/tests/Paramore.Brighter.RMQ.Tests/MessagingGateway/When_retry_limits_force_a_message_onto_the_DLQ.cs +++ b/tests/Paramore.Brighter.RMQ.Tests/MessagingGateway/When_retry_limits_force_a_message_onto_the_DLQ.cs @@ -89,7 +89,6 @@ public RMQMessageConsumerRetryDLQTests() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry() ); - var provider = new CommandProcessorProvider(commandProcessor); //pump messages from a channel to a handler - in essence we are building our own dispatcher in this test var messageMapperRegistry = new MessageMapperRegistry( @@ -99,7 +98,7 @@ public RMQMessageConsumerRetryDLQTests() messageMapperRegistry.Register(); - _messagePump = new Reactor(provider, messageMapperRegistry, + _messagePump = new Reactor(commandProcessor, messageMapperRegistry, new EmptyMessageTransformerFactory(), new InMemoryRequestContextFactory(), _channel) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 0 diff --git a/tests/Paramore.Brighter.RMQ.Tests/MessagingGateway/When_retry_limits_force_a_message_onto_the_DLQ_async.cs b/tests/Paramore.Brighter.RMQ.Tests/MessagingGateway/When_retry_limits_force_a_message_onto_the_DLQ_async.cs index 2d593c0ed7..2c7e950b73 100644 --- a/tests/Paramore.Brighter.RMQ.Tests/MessagingGateway/When_retry_limits_force_a_message_onto_the_DLQ_async.cs +++ b/tests/Paramore.Brighter.RMQ.Tests/MessagingGateway/When_retry_limits_force_a_message_onto_the_DLQ_async.cs @@ -88,7 +88,6 @@ public RMQMessageConsumerRetryDLQTestsAsync() requestContextFactory: new InMemoryRequestContextFactory(), policyRegistry: new PolicyRegistry() ); - var provider = new CommandProcessorProvider(commandProcessor); //pump messages from a channel to a handler - in essence we are building our own dispatcher in this test var messageMapperRegistry = new MessageMapperRegistry( @@ -98,7 +97,7 @@ public RMQMessageConsumerRetryDLQTestsAsync() messageMapperRegistry.RegisterAsync(); - _messagePump = new Proactor(provider, messageMapperRegistry, + _messagePump = new Proactor(commandProcessor, messageMapperRegistry, new EmptyMessageTransformerFactoryAsync(), new InMemoryRequestContextFactory(), _channel) { Channel = _channel, TimeOut = TimeSpan.FromMilliseconds(5000), RequeueCount = 3 From 966e981967ce3615556fbfba3317746ef08eff0f Mon Sep 17 00:00:00 2001 From: Paul Reardon Date: Fri, 3 Jan 2025 21:11:59 +0000 Subject: [PATCH 4/8] Add ADR --- ...dependencies-inline-with-lifetime-scope.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 docs/adr/0023-Scoping-dependencies-inline-with-lifetime-scope.md diff --git a/docs/adr/0023-Scoping-dependencies-inline-with-lifetime-scope.md b/docs/adr/0023-Scoping-dependencies-inline-with-lifetime-scope.md new file mode 100644 index 0000000000..d666120c80 --- /dev/null +++ b/docs/adr/0023-Scoping-dependencies-inline-with-lifetime-scope.md @@ -0,0 +1,19 @@ +# 23. Scoping dependencies inline with lifetime scope + +Date: 2025-01-03 + +## Status + +Proposed + +## Context + +As it stands dependency Lifetime Scopes are wrapped around the `Command Processor` meaning that all options performed by an instance of the Command processor will share the same scope, this becomes problematic when using the `Publish` method as this allows for multiple `Request Handlers` to be subscribed to a single Event, this will mean that all handlers share dependencies in the same scope which is unexpected behavior. + +## Decision + +When the Handler Factories are configured to not be a singleton Scopes will be created for each Lifetime, and a new lifetime will be given for each registered subscriber. + +## Consequences + +We will no longer require a `Command processor provider` as this was only created for scoping, and Handler factories will require the lifetime scope to be passed in to all methods. From 149663c2d24f3c2599874014cbb0c16f5bce36ef Mon Sep 17 00:00:00 2001 From: Paul Reardon Date: Fri, 3 Jan 2025 21:15:01 +0000 Subject: [PATCH 5/8] Remove unused Pipeline --- src/Paramore.Brighter/Pipelines.cs | 49 ------------------------------ 1 file changed, 49 deletions(-) delete mode 100644 src/Paramore.Brighter/Pipelines.cs diff --git a/src/Paramore.Brighter/Pipelines.cs b/src/Paramore.Brighter/Pipelines.cs deleted file mode 100644 index 6f1426bd5b..0000000000 --- a/src/Paramore.Brighter/Pipelines.cs +++ /dev/null @@ -1,49 +0,0 @@ -#region Licence -/* The MIT License (MIT) -Copyright © 2014 Ian Cooper - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the “Software”), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. */ - -#endregion - -using System.Collections; -using System.Collections.Generic; - -namespace Paramore.Brighter -{ - public class Pipelines : IEnumerable> where TRequest : class, IRequest - { - private readonly List> _filters = new List>(); - - public IEnumerator> GetEnumerator() - { - return _filters.GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - - public void Add(IHandleRequests handler) - { - _filters.Add(handler); - } - } -} From 5a0a8cbf55c1118a9bc9f094a8205380f32e4789 Mon Sep 17 00:00:00 2001 From: Paul Reardon Date: Sat, 4 Jan 2025 15:51:16 +0000 Subject: [PATCH 6/8] Bring back Pipelines and simplify pipeline building --- src/Paramore.Brighter/CommandProcessor.cs | 83 ++++------- src/Paramore.Brighter/IAmAPipelineBuilder.cs | 3 +- .../IAmAnAsyncPipelineBuilder.cs | 3 +- src/Paramore.Brighter/IRequestContext.cs | 6 + src/Paramore.Brighter/PipelineBuilder.cs | 141 +++++++++++++----- src/Paramore.Brighter/Pipelines.cs | 49 ++++++ src/Paramore.Brighter/RequestContext.cs | 15 +- ..._A_Handler_Is_Part_Of_An_Async_Pipeline.cs | 10 +- .../When_A_Handler_Is_Part_of_A_Pipeline.cs | 10 +- .../When_Building_A_Handler_For_A_Command.cs | 10 +- ...Building_A_Handler_For_An_Async_Command.cs | 10 +- ...lding_A_Pipeline_Allow_ForiegnAttribues.cs | 10 +- ...ing_A_Pipeline_Allow_Pre_And_Post_Tasks.cs | 10 +- ..._Failures_Should_Be_ConfigurationErrors.cs | 11 +- ..._Building_A_Pipeline_Preserve_The_Order.cs | 10 +- ...n_Building_A_Pipeline_With_Global_Inbox.cs | 13 +- ...With_Global_Inbox_And_NoInbox_Attribute.cs | 13 +- ...obal_Inbox_And_NoInbox_Attribute_Async .cs | 13 +- ...ipeline_With_Global_Inbox_And_Use_Inbox.cs | 13 +- ...e_With_Global_Inbox_And_Use_Inbox_Async.cs | 14 +- ...ding_A_Pipeline_With_Global_Inbox_Async.cs | 12 +- ...line_With_Global_Inbox_Override_Context.cs | 13 +- ...A_Sync_Pipeline_That_Has_Async_Handlers.cs | 10 +- ...n_Async_Pipeline_Allow_ForiegnAttribues.cs | 10 +- ...Async_Pipeline_Allow_Pre_And_Post_Tasks.cs | 10 +- ..._Failures_Should_Be_ConfigurationErrors.cs | 11 +- ...ng_An_Async_Pipeline_Preserve_The_Order.cs | 10 +- ...n_Async_Pipeline_That_Has_Sync_Handlers.cs | 10 +- ..._Finding_A_Hander_That_Has_Dependencies.cs | 10 +- .../When_Finding_A_Handler_For_A_Command.cs | 10 +- ...cised_The_Pipeline_Cleanup_Its_Handlers.cs | 15 +- 31 files changed, 310 insertions(+), 258 deletions(-) create mode 100644 src/Paramore.Brighter/Pipelines.cs diff --git a/src/Paramore.Brighter/CommandProcessor.cs b/src/Paramore.Brighter/CommandProcessor.cs index 0d96db3bb0..2345970d02 100644 --- a/src/Paramore.Brighter/CommandProcessor.cs +++ b/src/Paramore.Brighter/CommandProcessor.cs @@ -236,21 +236,16 @@ public void Send(T command, RequestContext? requestContext = null) where T : if (_subscriberRegistry is null) throw new ArgumentException("A subscriberRegistry must be configured."); - var observers = _subscriberRegistry.Get(); - - var handlerCount = observers.Count(); - - using var builder = new PipelineBuilder(_handlerFactorySync, _inboxConfiguration); + using var builder = new PipelineBuilder(_subscriberRegistry, _handlerFactorySync, _inboxConfiguration); try { s_logger.LogInformation("Building send pipeline for command: {CommandType} {Id}", command.GetType(), command.Id); - - AssertValidSendPipeline(command, handlerCount); - - var handler = builder.Build(observers.First(), context); + var handlerChain = builder.Build(context); + + AssertValidSendPipeline(command, handlerChain.Count()); - handler.Handle(command); + handlerChain.First().Handle(command); } catch (Exception e) { @@ -288,22 +283,17 @@ public async Task SendAsync( if (_subscriberRegistry is null) throw new ArgumentException("A subscriberRegistry must be configured."); - - var observers = _subscriberRegistry.Get(); - - var handlerCount = observers.Count(); - using var builder = new PipelineBuilder(_handlerFactoryAsync, _inboxConfiguration); + using var builder = new PipelineBuilder(_subscriberRegistry, _handlerFactoryAsync, _inboxConfiguration); try { s_logger.LogInformation("Building send async pipeline for command: {CommandType} {Id}", command.GetType(), command.Id); - - AssertValidSendPipeline(command, handlerCount); - - var handler = builder.BuildAsync(observers.First(), context, continueOnCapturedContext); + var handlerChain = builder.BuildAsync(context, continueOnCapturedContext); - await handler.HandleAsync(command, cancellationToken) + AssertValidSendPipeline(command, handlerChain.Count()); + + await handlerChain.First().HandleAsync(command, cancellationToken) .ConfigureAwait(continueOnCapturedContext); } catch (Exception e) @@ -341,29 +331,23 @@ public void Publish(T @event, RequestContext? requestContext = null) where T if (_subscriberRegistry is null) throw new ArgumentException("A subscriberRegistry must be configured."); - var observers = _subscriberRegistry.Get(); - - var handlerCount = observers.Count(); - + using var builder = new PipelineBuilder(_subscriberRegistry, _handlerFactorySync, _inboxConfiguration); + s_logger.LogInformation("Building send pipeline for event: {EventType} {Id}", @event.GetType(), + @event.Id); + var handlerChain = builder.Build(context); + + var handlerCount = handlerChain.Count(); + s_logger.LogInformation("Found {HandlerCount} pipelines for event: {EventType} {Id}", handlerCount, @event.GetType(), @event.Id); var exceptions = new ConcurrentBag(); - // Parallel.ForEach(handlerChain, (handleRequests) => - // { - foreach (Type observer in observers) + Parallel.ForEach(handlerChain, (handleRequests) => { - s_logger.LogInformation("Building send pipeline for event: {EventType} {Id}", @event.GetType(), - @event.Id); - - using var builder = new PipelineBuilder(_handlerFactorySync, _inboxConfiguration); - - var handleRequests = builder.Build(observer, context); try { var handlerName = handleRequests.Name.ToString(); - handlerSpans[handlerName] = _tracer?.CreateSpan(CommandProcessorSpanOperation.Publish, @event, - span, options: _instrumentationOptions)!; + handlerSpans[handlerName] = _tracer?.CreateSpan(CommandProcessorSpanOperation.Publish, @event, span, options: _instrumentationOptions)!; context.Span = handlerSpans[handlerName]; handleRequests.Handle(@event); context.Span = span; @@ -372,8 +356,7 @@ public void Publish(T @event, RequestContext? requestContext = null) where T { exceptions.Add(e); } - } - // }); + }); _tracer?.LinkSpans(handlerSpans); @@ -421,32 +404,30 @@ public async Task PublishAsync( if (_subscriberRegistry is null) throw new ArgumentException("A subscriberRegistry must be configured."); - var observers = _subscriberRegistry.Get(); - - var handlerCount = observers.Count(); - - s_logger.LogInformation("Found {0} async pipelines for event: {EventType} {Id}", handlerCount, - @event.GetType(), @event.Id); - + using var builder = new PipelineBuilder(_subscriberRegistry, _handlerFactoryAsync, _inboxConfiguration); var handlerSpans = new ConcurrentDictionary(); try { s_logger.LogInformation("Building send async pipeline for event: {EventType} {Id}", @event.GetType(), @event.Id); + var handlerChain = builder.BuildAsync(context, continueOnCapturedContext); + var handlerCount = handlerChain.Count(); + + s_logger.LogInformation("Found {0} async pipelines for event: {EventType} {Id}", handlerCount, + @event.GetType(), @event.Id + ); + var exceptions = new ConcurrentBag(); try { var tasks = new List(); - foreach (var observer in observers) + foreach (var handleRequests in handlerChain) { - using var builder = new PipelineBuilder(_handlerFactoryAsync, _inboxConfiguration); - var handler = builder.BuildAsync(observer, context, continueOnCapturedContext); - - handlerSpans[handler.Name.ToString()] = _tracer?.CreateSpan(CommandProcessorSpanOperation.Publish, @event, span, options: _instrumentationOptions)!; - context.Span =handlerSpans[handler.Name.ToString()]; - tasks.Add(handler.HandleAsync(@event, cancellationToken)); + handlerSpans[handleRequests.Name.ToString()] = _tracer?.CreateSpan(CommandProcessorSpanOperation.Publish, @event, span, options: _instrumentationOptions)!; + context.Span =handlerSpans[handleRequests.Name.ToString()]; + tasks.Add(handleRequests.HandleAsync(@event, cancellationToken)); context.Span = span; } diff --git a/src/Paramore.Brighter/IAmAPipelineBuilder.cs b/src/Paramore.Brighter/IAmAPipelineBuilder.cs index 846d90c4ce..bff3a68e2a 100644 --- a/src/Paramore.Brighter/IAmAPipelineBuilder.cs +++ b/src/Paramore.Brighter/IAmAPipelineBuilder.cs @@ -38,9 +38,8 @@ internal interface IAmAPipelineBuilder : IDisposable where TRequest : /// /// Builds the specified request context. /// - /// The handler type to build /// The request context. /// Pipelines<TRequest>. - IHandleRequests Build(Type type, IRequestContext requestContext); + Pipelines Build(IRequestContext requestContext); } } diff --git a/src/Paramore.Brighter/IAmAnAsyncPipelineBuilder.cs b/src/Paramore.Brighter/IAmAnAsyncPipelineBuilder.cs index 3bb9344f19..e4a4e8e2da 100644 --- a/src/Paramore.Brighter/IAmAnAsyncPipelineBuilder.cs +++ b/src/Paramore.Brighter/IAmAnAsyncPipelineBuilder.cs @@ -39,10 +39,9 @@ internal interface IAmAnAsyncPipelineBuilder : IDisposable where TRequ /// /// Builds the specified request context. /// - /// The Handler Type /// The request context. /// Should we use the calling thread's synchronization context when continuing or a default thread synchronization context. Defaults to false /// - IHandleRequestsAsync BuildAsync(Type type, IRequestContext requestContext, bool continueOnCapturedContext); + AsyncPipelines BuildAsync(IRequestContext requestContext, bool continueOnCapturedContext); } } diff --git a/src/Paramore.Brighter/IRequestContext.cs b/src/Paramore.Brighter/IRequestContext.cs index 5695cce8be..54260b0f45 100644 --- a/src/Paramore.Brighter/IRequestContext.cs +++ b/src/Paramore.Brighter/IRequestContext.cs @@ -58,5 +58,11 @@ public interface IRequestContext /// Gets the Feature Switches /// IAmAFeatureSwitchRegistry? FeatureSwitches { get; } + + /// + /// Create a new copy of the Request Context + /// + /// a new copy of the request context + IRequestContext CreateCopy(); } } diff --git a/src/Paramore.Brighter/PipelineBuilder.cs b/src/Paramore.Brighter/PipelineBuilder.cs index dd932fd1ff..0ead46d96c 100644 --- a/src/Paramore.Brighter/PipelineBuilder.cs +++ b/src/Paramore.Brighter/PipelineBuilder.cs @@ -28,7 +28,6 @@ THE SOFTWARE. */ using System.Collections.Generic; using Paramore.Brighter.Extensions; using Paramore.Brighter.Logging; -using System.Reflection; using Microsoft.Extensions.Logging; using Paramore.Brighter.Inbox.Attributes; @@ -39,10 +38,11 @@ public class PipelineBuilder : IAmAPipelineBuilder, IAmAnAsy { private static readonly ILogger s_logger= ApplicationLogging.CreateLogger>(); + private readonly IAmASubscriberRegistry _subscriberRegistry; private readonly IAmAHandlerFactorySync? _handlerFactorySync; private readonly InboxConfiguration? _inboxConfiguration; - private readonly IAmALifetime _instanceScope; private readonly IAmAHandlerFactoryAsync? _asyncHandlerFactory; + private readonly List _instanceScopes = new List(); //GLOBAL! cache of handler attributes - won't change post-startup so avoid re-calculation. Method to clear cache below (if a broken test brought you here) private static readonly ConcurrentDictionary> s_preAttributesMemento = new ConcurrentDictionary>(); private static readonly ConcurrentDictionary> s_postAttributesMemento = new ConcurrentDictionary>(); @@ -51,37 +51,49 @@ public class PipelineBuilder : IAmAPipelineBuilder, IAmAnAsy /// Used to build a pipeline of handlers from the target handler and the attributes on that /// target handler which represent other filter steps in the pipeline /// + /// The subscriber registry /// Callback to the user code to create instances of handlers /// Do we have a global attribute to add an inbox public PipelineBuilder( + IAmASubscriberRegistry subscriberRegistry, IAmAHandlerFactorySync handlerFactorySync, InboxConfiguration? inboxConfiguration = null) { + _subscriberRegistry = subscriberRegistry; _handlerFactorySync = handlerFactorySync; _inboxConfiguration = inboxConfiguration; - _instanceScope = new HandlerLifetimeScope(handlerFactorySync); } public PipelineBuilder( + IAmASubscriberRegistry subscriberRegistry, IAmAHandlerFactoryAsync asyncHandlerFactory, InboxConfiguration? inboxConfiguration = null) { + _subscriberRegistry = subscriberRegistry; _asyncHandlerFactory = asyncHandlerFactory; _inboxConfiguration = inboxConfiguration; - _instanceScope = new HandlerLifetimeScope(asyncHandlerFactory); } - - public IHandleRequests Build(Type type, IRequestContext requestContext) + + public Pipelines Build(IRequestContext requestContext) { if(_handlerFactorySync is null) throw new NullReferenceException("HandlerFactorySync is null"); try { - var handler = (RequestHandler)_handlerFactorySync.Create(type, _instanceScope); - var pipeline = BuildPipeline(handler, requestContext); - pipeline.AddToLifetime(_instanceScope); - return pipeline; + var observers = _subscriberRegistry.Get(); + + var pipelines = new Pipelines(); + + observers.Each(observer => + { + var instanceScope = GetSyncInstanceScope(); + var handler = (RequestHandler)_handlerFactorySync.Create(observer, instanceScope); + var pipeline = BuildPipeline(handler, requestContext.CreateCopy(), instanceScope); + pipeline.AddToLifetime(instanceScope); + }); + + return pipelines; } catch (Exception e) when (e is not ConfigurationException) { @@ -102,11 +114,10 @@ public static void ClearPipelineCache() } public void Dispose() - { - _instanceScope.Dispose(); - } + => _instanceScopes.Each(s => s.Dispose()); - private IHandleRequests BuildPipeline(RequestHandler implicitHandler, IRequestContext requestContext) + private IHandleRequests BuildPipeline(RequestHandler implicitHandler, + IRequestContext requestContext, IAmALifetime instanceScope) { if (implicitHandler is null) { @@ -115,7 +126,8 @@ private IHandleRequests BuildPipeline(RequestHandler implici implicitHandler.Context = requestContext; - if (!s_preAttributesMemento.TryGetValue(implicitHandler.Name.ToString(), out IOrderedEnumerable? preAttributes)) + if (!s_preAttributesMemento.TryGetValue(implicitHandler.Name.ToString(), + out IOrderedEnumerable? preAttributes)) { preAttributes = implicitHandler.FindHandlerMethod() @@ -129,10 +141,11 @@ private IHandleRequests BuildPipeline(RequestHandler implici } - var firstInPipeline = PushOntoPipeline(preAttributes, implicitHandler, requestContext); + var firstInPipeline = PushOntoPipeline(preAttributes, implicitHandler, requestContext, instanceScope); - if (!s_postAttributesMemento.TryGetValue(implicitHandler.Name.ToString(), out IOrderedEnumerable? postAttributes)) + if (!s_postAttributesMemento.TryGetValue(implicitHandler.Name.ToString(), + out IOrderedEnumerable? postAttributes)) { postAttributes = implicitHandler.FindHandlerMethod() @@ -141,24 +154,34 @@ private IHandleRequests BuildPipeline(RequestHandler implici .OrderByDescending(attribute => attribute.Step); } - AppendToPipeline(postAttributes, implicitHandler, requestContext); + AppendToPipeline(postAttributes, implicitHandler, requestContext, instanceScope); s_logger.LogDebug("New handler pipeline created: {HandlerName}", TracePipeline(firstInPipeline)); return firstInPipeline; } - public IHandleRequestsAsync BuildAsync(Type type, IRequestContext requestContext, bool continueOnCapturedContext) + public AsyncPipelines BuildAsync(IRequestContext requestContext, bool continueOnCapturedContext) { if(_asyncHandlerFactory is null) throw new NullReferenceException("AsyncHandlerFactory is null"); try { - var handler = (RequestHandlerAsync)_asyncHandlerFactory.Create(type, _instanceScope); - var pipeline = BuildAsyncPipeline(handler, requestContext, continueOnCapturedContext); - pipeline.AddToLifetime(_instanceScope); - return pipeline; + var observers = _subscriberRegistry.Get(); + + var pipelines = new AsyncPipelines(); + + observers.Each(observer => + { + var instanceScope = GetAsyncInstanceScope(); + var handler = (RequestHandlerAsync)_asyncHandlerFactory.Create(observer, instanceScope); + var pipeline = BuildAsyncPipeline(handler, requestContext.CreateCopy(), instanceScope, + continueOnCapturedContext); + pipeline.AddToLifetime(instanceScope); + }); + + return pipelines; } catch (Exception e) when(!(e is ConfigurationException)) { @@ -166,7 +189,7 @@ public IHandleRequestsAsync BuildAsync(Type type, IRequestContext requ } } - private IHandleRequestsAsync BuildAsyncPipeline(RequestHandlerAsync implicitHandler, IRequestContext requestContext, bool continueOnCapturedContext) + private IHandleRequestsAsync BuildAsyncPipeline(RequestHandlerAsync implicitHandler, IRequestContext requestContext, IAmALifetime instanceScope, bool continueOnCapturedContext) { if (implicitHandler is null) { @@ -193,7 +216,7 @@ private IHandleRequestsAsync BuildAsyncPipeline(RequestHandlerAsync? postAttributes)) { @@ -204,7 +227,7 @@ private IHandleRequestsAsync BuildAsyncPipeline(RequestHandlerAsync attribute.Step); } - AppendToAsyncPipeline(postAttributes, implicitHandler, requestContext); + AppendToAsyncPipeline(postAttributes, implicitHandler, requestContext, instanceScope); s_logger.LogDebug("New async handler pipeline created: {HandlerName}", TracePipeline(firstInPipeline)); return firstInPipeline; } @@ -256,7 +279,7 @@ private void AddGlobalInboxAttributesAsync(ref IOrderedEnumerable attributes, IHandleRequests implicitHandler, IRequestContext requestContext) + private void AppendToPipeline(IEnumerable attributes, IHandleRequests implicitHandler, IRequestContext requestContext, IAmALifetime instanceScope) { IHandleRequests lastInPipeline = implicitHandler; attributes.Each(attribute => @@ -265,7 +288,7 @@ private void AppendToPipeline(IEnumerable attributes, I if (handlerType.GetInterfaces().Contains(typeof(IHandleRequests))) { var decorator = - new HandlerFactory(attribute, _handlerFactorySync!, requestContext).CreateRequestHandler(_instanceScope); + new HandlerFactory(attribute, _handlerFactorySync!, requestContext).CreateRequestHandler(instanceScope); lastInPipeline.SetSuccessor(decorator); lastInPipeline = decorator; } @@ -277,7 +300,8 @@ private void AppendToPipeline(IEnumerable attributes, I }); } - private void AppendToAsyncPipeline(IEnumerable attributes, IHandleRequestsAsync implicitHandler, IRequestContext requestContext) + private void AppendToAsyncPipeline(IEnumerable attributes, + IHandleRequestsAsync implicitHandler, IRequestContext requestContext, IAmALifetime instanceScope) { IHandleRequestsAsync lastInPipeline = implicitHandler; attributes.Each(attribute => @@ -285,18 +309,23 @@ private void AppendToAsyncPipeline(IEnumerable attribut var handlerType = attribute.GetHandlerType(); if (handlerType.GetInterfaces().Contains(typeof(IHandleRequestsAsync))) { - var decorator = _asyncHandlerFactory!.CreateAsyncRequestHandler(attribute, requestContext, _instanceScope); + var decorator = + _asyncHandlerFactory!.CreateAsyncRequestHandler(attribute, requestContext, + instanceScope); lastInPipeline.SetSuccessor(decorator); lastInPipeline = decorator; } else { - var message = string.Format("All handlers in an async pipeline must derive from IHandleRequestsAsync. You cannot have a mixed pipeline by including handler {0}", handlerType.Name); + var message = + string.Format( + "All handlers in an async pipeline must derive from IHandleRequestsAsync. You cannot have a mixed pipeline by including handler {0}", + handlerType.Name); throw new ConfigurationException(message); } }); } - + private static void PushOntoAttributeList(ref IOrderedEnumerable preAttributes, RequestHandlerAttribute requestHandlerAttribute) { var attributeList = new List(); @@ -311,8 +340,9 @@ private static void PushOntoAttributeList(ref IOrderedEnumerable handler.Step); } - - private IHandleRequests PushOntoPipeline(IEnumerable attributes, IHandleRequests lastInPipeline, IRequestContext requestContext) + + private IHandleRequests PushOntoPipeline(IEnumerable attributes, + IHandleRequests lastInPipeline, IRequestContext requestContext, IAmALifetime instanceScope) { attributes.Each(attribute => { @@ -320,34 +350,45 @@ private IHandleRequests PushOntoPipeline(IEnumerable(attribute, _handlerFactorySync!, requestContext).CreateRequestHandler(_instanceScope); + new HandlerFactory(attribute, _handlerFactorySync!, requestContext) + .CreateRequestHandler(instanceScope); decorator.SetSuccessor(lastInPipeline); lastInPipeline = decorator; } else { - var message = string.Format("All handlers in a pipeline must derive from IHandleRequests. You cannot have a mixed pipeline by including handler {0}", handlerType.Name); + var message = + string.Format( + "All handlers in a pipeline must derive from IHandleRequests. You cannot have a mixed pipeline by including handler {0}", + handlerType.Name); throw new ConfigurationException(message); } }); return lastInPipeline; } - private IHandleRequestsAsync PushOntoAsyncPipeline(IEnumerable attributes, IHandleRequestsAsync lastInPipeline, IRequestContext requestContext, bool continueOnCapturedContext) + private IHandleRequestsAsync PushOntoAsyncPipeline(IEnumerable attributes, + IHandleRequestsAsync lastInPipeline, IRequestContext requestContext, IAmALifetime instanceScope, + bool continueOnCapturedContext) { attributes.Each(attribute => { var handlerType = attribute.GetHandlerType(); if (handlerType.GetInterfaces().Contains(typeof(IHandleRequestsAsync))) { - var decorator = _asyncHandlerFactory!.CreateAsyncRequestHandler(attribute, requestContext, _instanceScope); + var decorator = + _asyncHandlerFactory!.CreateAsyncRequestHandler(attribute, requestContext, + instanceScope); decorator.ContinueOnCapturedContext = continueOnCapturedContext; decorator.SetSuccessor(lastInPipeline); lastInPipeline = decorator; } else { - var message = string.Format("All handlers in an async pipeline must derive from IHandleRequestsAsync. You cannot have a mixed pipeline by including handler {0}", handlerType.Name); + var message = + string.Format( + "All handlers in an async pipeline must derive from IHandleRequestsAsync. You cannot have a mixed pipeline by including handler {0}", + handlerType.Name); throw new ConfigurationException(message); } }); @@ -367,5 +408,27 @@ private PipelineTracer TracePipeline(IHandleRequestsAsync firstInPipel firstInPipeline.DescribePath(pipelineTracer); return pipelineTracer; } + + private IAmALifetime GetSyncInstanceScope() + { + if(_handlerFactorySync is null) + throw new NullReferenceException("HandlerFactorySync is null"); + + var scope = new HandlerLifetimeScope(_handlerFactorySync); + _instanceScopes.Add(scope); + + return scope; + } + + private IAmALifetime GetAsyncInstanceScope() + { + if(_asyncHandlerFactory is null) + throw new NullReferenceException("AsyncHandlerFactory is null"); + + var scope = new HandlerLifetimeScope(_asyncHandlerFactory); + _instanceScopes.Add(scope); + + return scope; + } } } diff --git a/src/Paramore.Brighter/Pipelines.cs b/src/Paramore.Brighter/Pipelines.cs new file mode 100644 index 0000000000..6f1426bd5b --- /dev/null +++ b/src/Paramore.Brighter/Pipelines.cs @@ -0,0 +1,49 @@ +#region Licence +/* The MIT License (MIT) +Copyright © 2014 Ian Cooper + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. */ + +#endregion + +using System.Collections; +using System.Collections.Generic; + +namespace Paramore.Brighter +{ + public class Pipelines : IEnumerable> where TRequest : class, IRequest + { + private readonly List> _filters = new List>(); + + public IEnumerator> GetEnumerator() + { + return _filters.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(IHandleRequests handler) + { + _filters.Add(handler); + } + } +} diff --git a/src/Paramore.Brighter/RequestContext.cs b/src/Paramore.Brighter/RequestContext.cs index 66eda57d0f..1cc550446a 100644 --- a/src/Paramore.Brighter/RequestContext.cs +++ b/src/Paramore.Brighter/RequestContext.cs @@ -51,7 +51,20 @@ public class RequestContext : IRequestContext /// Gets the Feature Switches /// public IAmAFeatureSwitchRegistry? FeatureSwitches { get; set; } - + + /// + /// Create a new instance of the Request Context + /// + /// New Instance of the message + public IRequestContext CreateCopy() + => new RequestContext + { + Span = Span, + Policies = Policies, + FeatureSwitches = FeatureSwitches, + OriginatingMessage = OriginatingMessage + }; + /// /// When we pass a requestContext through a receiver pipeline, we may want to pass the original message that started the pipeline. /// This is primarily useful for debugging - how did we get to this request?. But it is also useful for some request metadata that we diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_Of_An_Async_Pipeline.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_Of_An_Async_Pipeline.cs index 44c49e4e12..ec1ad03df4 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_Of_An_Async_Pipeline.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_Of_An_Async_Pipeline.cs @@ -37,12 +37,11 @@ public class PipelineBuilderAsyncTests : IDisposable { private readonly PipelineBuilder _pipelineBuilder; private IHandleRequestsAsync _pipeline; - private SubscriberRegistry _subscriberRegistry; public PipelineBuilderAsyncTests() { - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.RegisterAsync(); + var registry = new SubscriberRegistry(); + registry.RegisterAsync(); var container = new ServiceCollection(); container.AddTransient(); @@ -51,7 +50,7 @@ public PipelineBuilderAsyncTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder((IAmAHandlerFactoryAsync)handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory); PipelineBuilder.ClearPipelineCache(); } @@ -59,8 +58,7 @@ public PipelineBuilderAsyncTests() [Fact] public void When_A_Handler_Is_Part_Of_An_Async_Pipeline() { - var observers = _subscriberRegistry.Get(); - _pipeline = _pipelineBuilder.BuildAsync(observers.First(), new RequestContext(), false); + _pipeline = _pipelineBuilder.BuildAsync(new RequestContext(), false).First(); TracePipeline().ToString().Should().Contain("MyImplicitHandlerAsync"); TracePipeline().ToString().Should().Contain("MyLoggingHandlerAsync"); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_of_A_Pipeline.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_of_A_Pipeline.cs index 54bed1d637..4e1144f738 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_of_A_Pipeline.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_A_Handler_Is_Part_of_A_Pipeline.cs @@ -37,12 +37,11 @@ public class PipelineBuilderTests : IDisposable { private readonly PipelineBuilder _pipelineBuilder; private IHandleRequests _pipeline; - private SubscriberRegistry _subscriberRegistry; public PipelineBuilderTests() { - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.Register(); + var registry = new SubscriberRegistry(); + registry.Register(); var container = new ServiceCollection(); container.AddTransient(); @@ -51,15 +50,14 @@ public PipelineBuilderTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder((IAmAHandlerFactorySync)handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_A_Handler_Is_Part_of_A_Pipeline() { - var observers = _subscriberRegistry.Get(); - _pipeline = _pipelineBuilder.Build(observers.First(), new RequestContext()); + _pipeline = _pipelineBuilder.Build(new RequestContext()).First(); TracePipeline().ToString().Should().Contain("MyImplicitHandler"); TracePipeline().ToString().Should().Contain("MyLoggingHandler"); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Handler_For_A_Command.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Handler_For_A_Command.cs index 2d12fe6ced..0430fb99b3 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Handler_For_A_Command.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Handler_For_A_Command.cs @@ -36,24 +36,22 @@ public class PipelineForCommandTests : IDisposable private readonly PipelineBuilder _chainBuilder; private IHandleRequests _chainOfResponsibility; private readonly RequestContext _requestContext; - private SubscriberRegistry _subscriberRegistry; public PipelineForCommandTests() { - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.Register(); + var registry = new SubscriberRegistry(); + registry.Register(); var handlerFactory = new SimpleHandlerFactorySync(_ => new MyCommandHandler()); _requestContext = new RequestContext(); - _chainBuilder = new PipelineBuilder(handlerFactory); + _chainBuilder = new PipelineBuilder(registry, handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_Building_A_Handler_For_A_Command() { - var observers = _subscriberRegistry.Get(); - _chainOfResponsibility = _chainBuilder.Build(observers.First(), _requestContext); + _chainOfResponsibility = _chainBuilder.Build(_requestContext).First(); _chainOfResponsibility.Context.Should().NotBeNull(); _chainOfResponsibility.Context.Should().BeSameAs(_requestContext); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Handler_For_An_Async_Command.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Handler_For_An_Async_Command.cs index 4a04a92d4f..668d3c646f 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Handler_For_An_Async_Command.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Handler_For_An_Async_Command.cs @@ -38,23 +38,21 @@ public class PipelineForCommandAsyncTests : IDisposable private static IHandleRequestsAsync _chainOfResponsibility; private static RequestContext _requestContext; private readonly IDictionary _receivedMessages = new Dictionary(); - private SubscriberRegistry _subscriberRegistry; public PipelineForCommandAsyncTests() { - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.RegisterAsync(); + var registry = new SubscriberRegistry(); + registry.RegisterAsync(); var handlerFactory = new SimpleHandlerFactoryAsync(_ => new MyCommandHandlerAsync(_receivedMessages)); _requestContext = new RequestContext(); - _chainBuilder = new PipelineBuilder(asyncHandlerFactory: handlerFactory); + _chainBuilder = new PipelineBuilder(registry, asyncHandlerFactory: handlerFactory); } [Fact] public void When_Building_A_Handler_For_An_Async_Command() { - var observers = _subscriberRegistry.Get(); - _chainOfResponsibility = _chainBuilder.BuildAsync(observers.First(), _requestContext, false); + _chainOfResponsibility = _chainBuilder.BuildAsync(_requestContext, false).First(); _chainOfResponsibility.Context.Should().NotBeNull(); _chainOfResponsibility.Context.Should().BeSameAs(_requestContext); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_ForiegnAttribues.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_ForiegnAttribues.cs index d829b45f46..73e592004c 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_ForiegnAttribues.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_ForiegnAttribues.cs @@ -37,12 +37,11 @@ public class PipelineForeignAttributesTests : IDisposable { private readonly PipelineBuilder _pipelineBuilder; private IHandleRequests _pipeline; - private SubscriberRegistry _subscriberRegistry; public PipelineForeignAttributesTests() { - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.Register(); + var registry = new SubscriberRegistry(); + registry.Register(); var container = new ServiceCollection(); container.AddTransient(); @@ -52,15 +51,14 @@ public PipelineForeignAttributesTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder((IAmAHandlerFactorySync)handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_Building_A_Pipeline_Allow_ForeignAttributes() { - var observers = _subscriberRegistry.Get(); - _pipeline = _pipelineBuilder.Build(observers.First(), new RequestContext()); + _pipeline = _pipelineBuilder.Build(new RequestContext()).First(); TraceFilters().ToString().Should().Be("MyValidationHandler`1|MyObsoleteCommandHandler|MyLoggingHandler`1|"); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_Pre_And_Post_Tasks.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_Pre_And_Post_Tasks.cs index 5c7fa1bd64..bbe79cf7bc 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_Pre_And_Post_Tasks.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Allow_Pre_And_Post_Tasks.cs @@ -38,12 +38,11 @@ public class PipelinePreAndPostFiltersTests : IDisposable { private readonly PipelineBuilder _pipelineBuilder; private IHandleRequests _pipeline; - private SubscriberRegistry _subscriberRegistry; public PipelinePreAndPostFiltersTests() { - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.Register(); + var registry = new SubscriberRegistry(); + registry.Register(); var container = new ServiceCollection(); container.AddTransient(); @@ -53,15 +52,14 @@ public PipelinePreAndPostFiltersTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder((IAmAHandlerFactorySync)handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_Building_A_Pipeline_Allow_Pre_And_Post_Tasks() { - var observers = _subscriberRegistry.Get(); - _pipeline = _pipelineBuilder.Build(observers.First(), new RequestContext()); + _pipeline = _pipelineBuilder.Build(new RequestContext()).First(); TraceFilters().ToString().Should().Be("MyValidationHandler`1|MyPreAndPostDecoratedHandler|MyLoggingHandler`1|"); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Failures_Should_Be_ConfigurationErrors.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Failures_Should_Be_ConfigurationErrors.cs index e1dc37f7de..a1e261736a 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Failures_Should_Be_ConfigurationErrors.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Failures_Should_Be_ConfigurationErrors.cs @@ -1,5 +1,4 @@ using System; -using System.Linq; using FluentAssertions; using Paramore.Brighter.Core.Tests.CommandProcessors.TestDoubles; using Paramore.Brighter.Core.Tests.TestHelpers; @@ -11,26 +10,24 @@ public class BuildPipelineFaults { private readonly PipelineBuilder _chainBuilder; private readonly RequestContext _requestContext; - private SubscriberRegistry _subscriberRegistry; public BuildPipelineFaults() { - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.Register(); + var registry = new SubscriberRegistry(); + registry.Register(); //We'll simulate an IoC error var handlerFactory = new SimpleHandlerFactorySync(_ => throw new InvalidOperationException("Could no create handler")); _requestContext = new RequestContext(); - _chainBuilder = new PipelineBuilder(handlerFactory); + _chainBuilder = new PipelineBuilder(registry, handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_Building_A_Pipeline_Failures_Should_Be_ConfigurationErrors() { - var observers = _subscriberRegistry.Get(); - var exception = Catch.Exception(() => _chainBuilder.Build(observers.First(), _requestContext)); + var exception = Catch.Exception(() => _chainBuilder.Build(_requestContext)); exception.Should().NotBeNull(); exception.Should().BeOfType(); exception.InnerException.Should().BeOfType(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Preserve_The_Order.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Preserve_The_Order.cs index 39286aa736..924e307ea6 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Preserve_The_Order.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_Preserve_The_Order.cs @@ -37,12 +37,11 @@ public class PipelineOrderingTests : IDisposable { private readonly PipelineBuilder _pipelineBuilder; private IHandleRequests _pipeline; - private SubscriberRegistry _subscriberRegistry; public PipelineOrderingTests() { - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.Register(); + var registry = new SubscriberRegistry(); + registry.Register(); var container = new ServiceCollection(); container.AddTransient(); @@ -52,14 +51,13 @@ public PipelineOrderingTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder((IAmAHandlerFactorySync)handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory); } [Fact] public void When_Building_A_Pipeline_Preserve_The_Order() { - var observers = _subscriberRegistry.Get(); - _pipeline = _pipelineBuilder.Build(observers.First(), new RequestContext()); + _pipeline = _pipelineBuilder.Build(new RequestContext()).First(); PipelineTracer().ToString().Should().Be("MyLoggingHandler`1|MyValidationHandler`1|MyDoubleDecoratedHandler|"); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox.cs index 3928856cfb..bc9787794a 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Linq; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; @@ -15,16 +14,15 @@ namespace Paramore.Brighter.Core.Tests.CommandProcessors.Pipeline public class PipelineGlobalInboxTests : IDisposable { private readonly PipelineBuilder _chainBuilder; - private IEnumerable> _chainOfResponsibility; + private Pipelines _chainOfResponsibility; private readonly RequestContext _requestContext; - private SubscriberRegistry _subscriberRegistry; public PipelineGlobalInboxTests() { IAmAnInboxSync inbox = new InMemoryInbox(new FakeTimeProvider()); - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.Register(); + var registry = new SubscriberRegistry(); + registry.Register(); var container = new ServiceCollection(); container.AddTransient(); @@ -38,7 +36,7 @@ public PipelineGlobalInboxTests() InboxConfiguration inboxConfiguration = new(); - _chainBuilder = new PipelineBuilder((IAmAHandlerFactorySync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, inboxConfiguration); PipelineBuilder.ClearPipelineCache(); } @@ -46,8 +44,7 @@ public PipelineGlobalInboxTests() public void When_Building_A_Pipeline_With_Global_inbox() { //act - var observers = _subscriberRegistry.Get(); - _chainOfResponsibility = observers.Select(o => _chainBuilder.Build(o, _requestContext)); + _chainOfResponsibility = _chainBuilder.Build(_requestContext); //assert var tracer = TracePipeline(_chainOfResponsibility.First()); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute.cs index 1d7d9de9f9..567e343719 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Linq; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; @@ -14,17 +13,16 @@ namespace Paramore.Brighter.Core.Tests.CommandProcessors.Pipeline public class PipelineGlobalInboxNoInboxAttributeTests : IDisposable { private readonly PipelineBuilder _chainBuilder; - private IEnumerable> _chainOfResponsibility; + private Pipelines _chainOfResponsibility; private readonly RequestContext _requestContext; - private SubscriberRegistry _subscriberRegistry; public PipelineGlobalInboxNoInboxAttributeTests() { IAmAnInboxSync inbox = new InMemoryInbox(new FakeTimeProvider()); - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.Register(); + var registry = new SubscriberRegistry(); + registry.Register(); var container = new ServiceCollection(); container.AddTransient(); @@ -37,7 +35,7 @@ public PipelineGlobalInboxNoInboxAttributeTests() InboxConfiguration inboxConfiguration = new(); - _chainBuilder = new PipelineBuilder((IAmAHandlerFactorySync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, inboxConfiguration); } @@ -45,8 +43,7 @@ public PipelineGlobalInboxNoInboxAttributeTests() public void When_Building_A_Pipeline_With_Global_Inbox() { //act - var observers = _subscriberRegistry.Get(); - _chainOfResponsibility = observers.Select(o => _chainBuilder.Build(o, _requestContext)); + _chainOfResponsibility = _chainBuilder.Build(_requestContext); //assert var tracer = TracePipeline(_chainOfResponsibility.First()); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute_Async .cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute_Async .cs index 08294af9bf..761ee42082 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute_Async .cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_NoInbox_Attribute_Async .cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Linq; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; @@ -14,17 +13,16 @@ namespace Paramore.Brighter.Core.Tests.CommandProcessors.Pipeline public class PipelineGlobalInboxNoInboxAttributeAsyncTests : IDisposable { private readonly PipelineBuilder _chainBuilder; - private IEnumerable> _chainOfResponsibility; + private AsyncPipelines _chainOfResponsibility; private readonly RequestContext _requestContext; - private SubscriberRegistry _subscriberRegistry; public PipelineGlobalInboxNoInboxAttributeAsyncTests() { IAmAnInboxSync inbox = new InMemoryInbox(new FakeTimeProvider()); - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.RegisterAsync(); + var registry = new SubscriberRegistry(); + registry.RegisterAsync(); var container = new ServiceCollection(); container.AddTransient(); @@ -37,7 +35,7 @@ public PipelineGlobalInboxNoInboxAttributeAsyncTests() InboxConfiguration inboxConfiguration = new(); - _chainBuilder = new PipelineBuilder((IAmAHandlerFactoryAsync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory, inboxConfiguration); } @@ -45,8 +43,7 @@ public PipelineGlobalInboxNoInboxAttributeAsyncTests() public void When_Building_A_Pipeline_With_Global_Inbox_Async() { //act - var observers = _subscriberRegistry.Get(); - _chainOfResponsibility = observers.Select(o => _chainBuilder.BuildAsync(o, _requestContext, false)); + _chainOfResponsibility = _chainBuilder.BuildAsync(_requestContext, false); //assert var tracer = TracePipelineAsync(_chainOfResponsibility.First()); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox.cs index eafd20afa2..c2cab952a0 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Linq; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; @@ -17,17 +16,16 @@ namespace Paramore.Brighter.Core.Tests.CommandProcessors.Pipeline public class PipelineGlobalInboxWhenUseInboxTests : IDisposable { private readonly PipelineBuilder _chainBuilder; - private IEnumerable> _chainOfResponsibility; + private Pipelines _chainOfResponsibility; private readonly RequestContext _requestContext; - private SubscriberRegistry _subscriberRegistry; public PipelineGlobalInboxWhenUseInboxTests() { IAmAnInboxSync inbox = new InMemoryInbox(new FakeTimeProvider()); - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.Register(); + var registry = new SubscriberRegistry(); + registry.Register(); var container = new ServiceCollection(); container.AddTransient(); @@ -45,7 +43,7 @@ public PipelineGlobalInboxWhenUseInboxTests() onceOnly: true, actionOnExists: OnceOnlyAction.Throw); - _chainBuilder = new PipelineBuilder((IAmAHandlerFactorySync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, inboxConfiguration); } @@ -60,8 +58,7 @@ public void When_Building_A_Pipeline_With_Global_Inbox() //act - var observers = _subscriberRegistry.Get(); - _chainOfResponsibility = observers.Select(o => _chainBuilder.Build(o, _requestContext)); + _chainOfResponsibility = _chainBuilder.Build(_requestContext); var chain = _chainOfResponsibility.First(); var myCommand = new MyCommand(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox_Async.cs index d5c1aaef47..790147ee5a 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_And_Use_Inbox_Async.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FluentAssertions; @@ -18,16 +17,16 @@ namespace Paramore.Brighter.Core.Tests.CommandProcessors.Pipeline public class PipelineGlobalInboxWhenUseInboxAsyncTests : IDisposable { private readonly PipelineBuilder _chainBuilder; - private IEnumerable> _chainOfResponsibility; + private AsyncPipelines _chainOfResponsibility; private readonly RequestContext _requestContext; - private SubscriberRegistry _subscriberRegistry; + public PipelineGlobalInboxWhenUseInboxAsyncTests() { IAmAnInboxSync inbox = new InMemoryInbox(new FakeTimeProvider()); - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.RegisterAsync(); + var registry = new SubscriberRegistry(); + registry.RegisterAsync(); var container = new ServiceCollection(); container.AddTransient(); @@ -46,7 +45,7 @@ public PipelineGlobalInboxWhenUseInboxAsyncTests() onceOnly: true, actionOnExists: OnceOnlyAction.Throw); - _chainBuilder = new PipelineBuilder((IAmAHandlerFactoryAsync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory, inboxConfiguration); } @@ -61,8 +60,7 @@ public async Task When_Building_A_Pipeline_With_Global_Inbox() //act - var observers = _subscriberRegistry.Get(); - _chainOfResponsibility = observers.Select(o => _chainBuilder.BuildAsync(o, _requestContext, false)); + _chainOfResponsibility = _chainBuilder.BuildAsync(_requestContext, false); var chain = _chainOfResponsibility.First(); var myCommand = new MyCommand(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Async.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Async.cs index 58baa3a534..b6773892e3 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Async.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Async.cs @@ -19,9 +19,8 @@ namespace Paramore.Brighter.Core.Tests.CommandProcessors.Pipeline public class PipelineGlobalInboxTestsAsync : IDisposable { private readonly PipelineBuilder _chainBuilder; - private IEnumerable> _chainOfResponsibility; + private AsyncPipelines _chainOfResponsibility; private readonly RequestContext _requestContext; - private SubscriberRegistry _subscriberRegistry; public PipelineGlobalInboxTestsAsync() @@ -29,8 +28,8 @@ public PipelineGlobalInboxTestsAsync() IAmAnInboxAsync inbox = new InMemoryInbox(new FakeTimeProvider()); var handler = new MyCommandHandlerAsync(new Dictionary()); - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.RegisterAsync(); + var registry = new SubscriberRegistry(); + registry.RegisterAsync(); var container = new ServiceCollection(); container.AddSingleton(handler); @@ -45,7 +44,7 @@ public PipelineGlobalInboxTestsAsync() InboxConfiguration inboxConfiguration = new(); - _chainBuilder = new PipelineBuilder((IAmAHandlerFactoryAsync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory, inboxConfiguration); } @@ -53,8 +52,7 @@ public PipelineGlobalInboxTestsAsync() public void When_Building_A_Pipeline_With_Global_Inbox() { //act - var observers = _subscriberRegistry.Get(); - _chainOfResponsibility = observers.Select(o => _chainBuilder.BuildAsync(o, _requestContext, false)); + _chainOfResponsibility = _chainBuilder.BuildAsync(_requestContext, false); //assert var tracer = TracePipeline(_chainOfResponsibility.First()); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Override_Context.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Override_Context.cs index 44ac076d37..85d869887c 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Override_Context.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Pipeline_With_Global_Inbox_Override_Context.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Linq; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; @@ -16,18 +15,17 @@ public class PipelineGlobalInboxContextTests : IDisposable { private const string CONTEXT_KEY = "TestHandlerNameOverride"; private readonly PipelineBuilder _chainBuilder; - private IEnumerable> _chainOfResponsibility; + private Pipelines _chainOfResponsibility; private readonly RequestContext _requestContext; private readonly IAmAnInboxSync _inbox; - private SubscriberRegistry _subscriberRegistry; public PipelineGlobalInboxContextTests() { _inbox = new InMemoryInbox(new FakeTimeProvider()); - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.Register(); + var registry = new SubscriberRegistry(); + registry.Register(); var container = new ServiceCollection(); container.AddTransient(); @@ -43,7 +41,7 @@ public PipelineGlobalInboxContextTests() scope: InboxScope.All, context: (handlerType) => CONTEXT_KEY); - _chainBuilder = new PipelineBuilder((IAmAHandlerFactorySync)handlerFactory, inboxConfiguration); + _chainBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory, inboxConfiguration); PipelineBuilder.ClearPipelineCache(); } @@ -52,8 +50,7 @@ public PipelineGlobalInboxContextTests() public void When_Building_A_Pipeline_With_Global_inbox() { //act - var observers = _subscriberRegistry.Get(); - _chainOfResponsibility = observers.Select(o => _chainBuilder.Build(o, _requestContext)); + _chainOfResponsibility = _chainBuilder.Build(_requestContext); var firstHandler = _chainOfResponsibility.First(); var myCommmand = new MyCommand(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Sync_Pipeline_That_Has_Async_Handlers.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Sync_Pipeline_That_Has_Async_Handlers.cs index 8f038d22bf..3c5f50d7a8 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Sync_Pipeline_That_Has_Async_Handlers.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_A_Sync_Pipeline_That_Has_Async_Handlers.cs @@ -39,12 +39,11 @@ public class PipelineMixedHandlersTests : IDisposable private readonly PipelineBuilder _pipelineBuilder; private IHandleRequests _pipeline; private Exception _exception; - private SubscriberRegistry _subscriberRegistry; public PipelineMixedHandlersTests() { - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.Register(); + var registry = new SubscriberRegistry(); + registry.Register(); var container = new ServiceCollection(); container.AddTransient(); @@ -53,7 +52,7 @@ public PipelineMixedHandlersTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder((IAmAHandlerFactorySync)handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactorySync)handlerFactory); PipelineBuilder.ClearPipelineCache(); } @@ -61,8 +60,7 @@ public PipelineMixedHandlersTests() [Fact] public void When_Building_A_Sync_Pipeline_That_Has_Async_Handlers() { - var observers = _subscriberRegistry.Get(); - _exception = Catch.Exception(() => _pipeline = _pipelineBuilder.Build(observers.First(), new RequestContext())); + _exception = Catch.Exception(() => _pipeline = _pipelineBuilder.Build(new RequestContext()).First()); _exception.Should().NotBeNull(); _exception.Should().BeOfType(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_ForiegnAttribues.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_ForiegnAttribues.cs index 46a6b03dd7..3c3a1645dd 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_ForiegnAttribues.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_ForiegnAttribues.cs @@ -14,12 +14,11 @@ public class PipelineForiegnAttributesAsyncTests :IDisposable { private readonly PipelineBuilder _pipeline_Builder; private IHandleRequestsAsync _pipeline; - private SubscriberRegistry _subscriberRegistry; public PipelineForiegnAttributesAsyncTests() { - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.RegisterAsync(); + var registry = new SubscriberRegistry(); + registry.RegisterAsync(); var container = new ServiceCollection(); @@ -30,15 +29,14 @@ public PipelineForiegnAttributesAsyncTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipeline_Builder = new PipelineBuilder((IAmAHandlerFactoryAsync)handlerFactory); + _pipeline_Builder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_Building_An_Async_Pipeline_Allow_ForeignAttributes() { - var observers = _subscriberRegistry.Get(); - _pipeline = _pipeline_Builder.BuildAsync(observers.First(), new RequestContext(), false); + _pipeline = _pipeline_Builder.BuildAsync(new RequestContext(), false).First(); TraceFilters().ToString().Should().Be("MyValidationHandlerAsync`1|MyObsoleteCommandHandlerAsync|MyLoggingHandlerAsync`1|"); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_Pre_And_Post_Tasks.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_Pre_And_Post_Tasks.cs index e304ff6c54..7e45dfc9a5 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_Pre_And_Post_Tasks.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Allow_Pre_And_Post_Tasks.cs @@ -13,12 +13,11 @@ public class PipelinePreAndPostFiltersAsyncTests : IDisposable { private readonly PipelineBuilder _pipelineBuilder; private IHandleRequestsAsync _pipeline; - private SubscriberRegistry _subscriberRegistry; public PipelinePreAndPostFiltersAsyncTests() { - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.RegisterAsync(); + var registry = new SubscriberRegistry(); + registry.RegisterAsync(); var container = new ServiceCollection(); container.AddTransient(); @@ -28,15 +27,14 @@ public PipelinePreAndPostFiltersAsyncTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder((IAmAHandlerFactoryAsync)handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry,(IAmAHandlerFactoryAsync)handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] private void When_Building_An_Async_Pipeline_Allow_Pre_And_Post_Tasks() { - var observers = _subscriberRegistry.Get(); - _pipeline = _pipelineBuilder.BuildAsync(observers.First(), new RequestContext(), false); + _pipeline = _pipelineBuilder.BuildAsync(new RequestContext(), false).First(); TraceFilters().ToString().Should().Be("MyValidationHandlerAsync`1|MyPreAndPostDecoratedHandlerAsync|MyLoggingHandlerAsync`1|"); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Failures_Should_Be_ConfigurationErrors.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Failures_Should_Be_ConfigurationErrors.cs index 7fd584b16f..638871d7bc 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Failures_Should_Be_ConfigurationErrors.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Failures_Should_Be_ConfigurationErrors.cs @@ -1,5 +1,4 @@ using System; -using System.Linq; using FluentAssertions; using Paramore.Brighter.Core.Tests.CommandProcessors.TestDoubles; using Paramore.Brighter.Core.Tests.TestHelpers; @@ -11,26 +10,24 @@ public class BuildPipelineFaultsAsync { private readonly PipelineBuilder _chainBuilder; private readonly RequestContext _requestContext; - private SubscriberRegistry _subscriberRegistry; public BuildPipelineFaultsAsync() { - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.RegisterAsync(); + var registry = new SubscriberRegistry(); + registry.RegisterAsync(); //We'll simulate an IoC error IAmAHandlerFactoryAsync handlerFactory = new SimpleHandlerFactoryAsync(_ => throw new InvalidOperationException("Could no create handler")); _requestContext = new RequestContext(); - _chainBuilder = new PipelineBuilder(handlerFactory); + _chainBuilder = new PipelineBuilder(registry, handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_Building_A_Pipeline_Failures_Should_Be_ConfigurationErrors() { - var observers = _subscriberRegistry.Get(); - var exception = Catch.Exception(() => _chainBuilder.BuildAsync(observers.First(), _requestContext, false)); + var exception = Catch.Exception(() => _chainBuilder.BuildAsync(_requestContext, false)); exception.Should().NotBeNull(); exception.Should().BeOfType(); exception.InnerException.Should().BeOfType(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Preserve_The_Order.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Preserve_The_Order.cs index f087984879..fbf4f2a3bc 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Preserve_The_Order.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_Preserve_The_Order.cs @@ -38,12 +38,11 @@ public class PipelineOrderingAsyncTests: IDisposable { private readonly PipelineBuilder _pipeline_Builder; private IHandleRequestsAsync _pipeline; - private SubscriberRegistry _subscriberRegistry; public PipelineOrderingAsyncTests() { - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.RegisterAsync(); + var registry = new SubscriberRegistry(); + registry.RegisterAsync(); var container = new ServiceCollection(); container.AddTransient(); @@ -53,15 +52,14 @@ public PipelineOrderingAsyncTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipeline_Builder = new PipelineBuilder((IAmAHandlerFactoryAsync)handlerFactory); + _pipeline_Builder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_Building_An_Async_Pipeline_Preserve_The_Order() { - var observers = _subscriberRegistry.Get(); - _pipeline = _pipeline_Builder.BuildAsync(observers.First(), new RequestContext(), false); + _pipeline = _pipeline_Builder.BuildAsync(new RequestContext(), false).First(); PipelineTracer().ToString().Should().Be("MyLoggingHandlerAsync`1|MyValidationHandlerAsync`1|MyDoubleDecoratedHandlerAsync|"); } diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_That_Has_Sync_Handlers.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_That_Has_Sync_Handlers.cs index 86647f8409..6f4f05617b 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_That_Has_Sync_Handlers.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Building_An_Async_Pipeline_That_Has_Sync_Handlers.cs @@ -15,12 +15,11 @@ public class PipelineMixedHandlersAsyncTests : IDisposable private readonly PipelineBuilder _pipelineBuilder; private IHandleRequestsAsync _pipeline; private Exception _exception; - private SubscriberRegistry _subscriberRegistry; public PipelineMixedHandlersAsyncTests() { - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.RegisterAsync(); + var registry = new SubscriberRegistry(); + registry.RegisterAsync(); var container = new ServiceCollection(); container.AddTransient(); @@ -30,15 +29,14 @@ public PipelineMixedHandlersAsyncTests() var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider()); - _pipelineBuilder = new PipelineBuilder((IAmAHandlerFactoryAsync)handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, (IAmAHandlerFactoryAsync)handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_Building_An_Async_Pipeline_That_Has_Sync_Handlers() { - var observers = _subscriberRegistry.Get(); - _exception = Catch.Exception(() => _pipeline = _pipelineBuilder.BuildAsync(observers.First(), new RequestContext(), false)); + _exception = Catch.Exception(() => _pipeline = _pipelineBuilder.BuildAsync(new RequestContext(), false).First()); _exception.Should().NotBeNull(); _exception.Should().BeOfType(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Hander_That_Has_Dependencies.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Hander_That_Has_Dependencies.cs index b273b1ae7a..8f52f7b0d1 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Hander_That_Has_Dependencies.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Hander_That_Has_Dependencies.cs @@ -12,24 +12,22 @@ public class PipelineWithHandlerDependenciesTests : IDisposable { private readonly PipelineBuilder _pipelineBuilder; private IHandleRequests _pipeline; - private SubscriberRegistry _subscriberRegistry; public PipelineWithHandlerDependenciesTests() { - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.Register(); + var registry = new SubscriberRegistry(); + registry.Register(); var handlerFactory = new SimpleHandlerFactorySync(_ => new MyDependentCommandHandler(new FakeRepository(new FakeSession()))); - _pipelineBuilder = new PipelineBuilder(handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_Finding_A_Handler_That_Has_Dependencies() { - var observers = _subscriberRegistry.Get(); - _pipeline = _pipelineBuilder.Build(observers.First(), new RequestContext()); + _pipeline = _pipelineBuilder.Build(new RequestContext()).First(); // _should_return_the_command_handler_as_the_implicit_handler _pipeline.Should().BeOfType(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command.cs index b0a4244c50..a17ae10d33 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_Finding_A_Handler_For_A_Command.cs @@ -35,23 +35,21 @@ public class PipelineBuildForCommandTests : IDisposable { private readonly PipelineBuilder _pipelineBuilder; private IHandleRequests _pipeline; - private SubscriberRegistry _subscriberRegistry; public PipelineBuildForCommandTests() { - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.Register(); + var registry = new SubscriberRegistry(); + registry.Register(); var handlerFactory = new SimpleHandlerFactorySync(_ => new MyCommandHandler()); - _pipelineBuilder = new PipelineBuilder(handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, handlerFactory); PipelineBuilder.ClearPipelineCache(); } [Fact] public void When_Finding_A_Handler_For_A_Command() { - var observers = _subscriberRegistry.Get(); - _pipeline = _pipelineBuilder.Build(observers.First(), new RequestContext()); + _pipeline = _pipelineBuilder.Build(new RequestContext()).First(); //_should_return_the_my_command_handler_as_the_implicit_handler _pipeline.Should().BeOfType(); diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_We_Have_Exercised_The_Pipeline_Cleanup_Its_Handlers.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_We_Have_Exercised_The_Pipeline_Cleanup_Its_Handlers.cs index e4633e860f..6277e77baa 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_We_Have_Exercised_The_Pipeline_Cleanup_Its_Handlers.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/Pipeline/When_We_Have_Exercised_The_Pipeline_Cleanup_Its_Handlers.cs @@ -11,26 +11,21 @@ public class PipelineCleanupTests : IDisposable { private readonly PipelineBuilder _pipelineBuilder; private static string s_released; - private SubscriberRegistry _subscriberRegistry; public PipelineCleanupTests() { s_released = string.Empty; - _subscriberRegistry = new SubscriberRegistry(); - _subscriberRegistry.Register(); - _subscriberRegistry.Register>(); + var registry = new SubscriberRegistry(); + registry.Register(); + registry.Register>(); var handlerFactory = new CheapHandlerFactorySync(); - _pipelineBuilder = new PipelineBuilder(handlerFactory); + _pipelineBuilder = new PipelineBuilder(registry, handlerFactory); PipelineBuilder.ClearPipelineCache(); - var observers = _subscriberRegistry.Get(); - foreach (var observer in observers) - { - _pipelineBuilder.Build(observer, new RequestContext()); - } + _pipelineBuilder.Build(new RequestContext()).Any(); } [Fact] From fb81b76e443f290082cffbbd39549afe189b2e5d Mon Sep 17 00:00:00 2001 From: Paul Reardon Date: Sat, 4 Jan 2025 15:59:07 +0000 Subject: [PATCH 7/8] Have Factory work for Scoped as well as Transient --- ...coping-dependencies-inline-with-lifetime-scope.md | 2 +- .../ServiceProviderHandlerFactory.cs | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/adr/0023-Scoping-dependencies-inline-with-lifetime-scope.md b/docs/adr/0023-Scoping-dependencies-inline-with-lifetime-scope.md index d666120c80..4265fd41ea 100644 --- a/docs/adr/0023-Scoping-dependencies-inline-with-lifetime-scope.md +++ b/docs/adr/0023-Scoping-dependencies-inline-with-lifetime-scope.md @@ -16,4 +16,4 @@ When the Handler Factories are configured to not be a singleton Scopes will be c ## Consequences -We will no longer require a `Command processor provider` as this was only created for scoping, and Handler factories will require the lifetime scope to be passed in to all methods. +We will no longer require a `Command processor provider` as this was only created for scoping, and Handler factories will require the lifetime scope to be passed in to all methods so it can use this for managing scopes. diff --git a/src/Paramore.Brighter.Extensions.DependencyInjection/ServiceProviderHandlerFactory.cs b/src/Paramore.Brighter.Extensions.DependencyInjection/ServiceProviderHandlerFactory.cs index 66b97053e9..fed171b611 100644 --- a/src/Paramore.Brighter.Extensions.DependencyInjection/ServiceProviderHandlerFactory.cs +++ b/src/Paramore.Brighter.Extensions.DependencyInjection/ServiceProviderHandlerFactory.cs @@ -34,7 +34,7 @@ namespace Paramore.Brighter.Extensions.DependencyInjection public class ServiceProviderHandlerFactory : IAmAHandlerFactorySync, IAmAHandlerFactoryAsync { private readonly IServiceProvider _serviceProvider; - private readonly bool _isTransient; + private readonly bool _isSingleton; private readonly Dictionary _scopes = new Dictionary(); /// @@ -45,7 +45,7 @@ public ServiceProviderHandlerFactory(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; var options = (IBrighterOptions) serviceProvider.GetService(typeof(IBrighterOptions)); - if (options == null) _isTransient = true; else _isTransient = options.HandlerLifetime == ServiceLifetime.Transient; + if (options == null) _isSingleton = false; else _isSingleton = options.HandlerLifetime == ServiceLifetime.Singleton; } /// @@ -57,7 +57,7 @@ public ServiceProviderHandlerFactory(IServiceProvider serviceProvider) /// An instantiated request handler IHandleRequests IAmAHandlerFactorySync.Create(Type handlerType, IAmALifetime lifetime) { - if (!_isTransient) + if (_isSingleton) return (IHandleRequests)_serviceProvider.GetService(handlerType); if (!_scopes.ContainsKey(lifetime)) @@ -75,7 +75,7 @@ IHandleRequests IAmAHandlerFactorySync.Create(Type handlerType, IAmALifetime lif /// An instantiated request handler IHandleRequestsAsync IAmAHandlerFactoryAsync.Create(Type handlerType, IAmALifetime lifetime) { - if (!_isTransient) + if (_isSingleton) return (IHandleRequestsAsync)_serviceProvider.GetService(handlerType); if (!_scopes.ContainsKey(lifetime)) @@ -91,7 +91,7 @@ IHandleRequestsAsync IAmAHandlerFactoryAsync.Create(Type handlerType, IAmALifeti /// The brighter Handler lifetime public void Release(IHandleRequests handler, IAmALifetime lifetime) { - if (!_isTransient) return; + if (_isSingleton) return; var disposal = handler as IDisposable; disposal?.Dispose(); @@ -101,7 +101,7 @@ public void Release(IHandleRequests handler, IAmALifetime lifetime) public void Release(IHandleRequestsAsync handler, IAmALifetime lifetime) { - if (!_isTransient) return; + if (_isSingleton) return; var disposal = handler as IDisposable; disposal?.Dispose(); From 86f08484c383c14d5118013e847473e629fe06dd Mon Sep 17 00:00:00 2001 From: Paul Reardon Date: Sat, 4 Jan 2025 21:50:00 +0000 Subject: [PATCH 8/8] Fix Tests --- src/Paramore.Brighter/CommandProcessor.cs | 14 +++++++++----- src/Paramore.Brighter/PipelineBuilder.cs | 10 ++++++++-- src/Paramore.Brighter/RequestContext.cs | 9 ++++++++- .../When_No_Request_Context_Is_Provided.cs | 4 ++-- 4 files changed, 27 insertions(+), 10 deletions(-) diff --git a/src/Paramore.Brighter/CommandProcessor.cs b/src/Paramore.Brighter/CommandProcessor.cs index 2345970d02..f044cd106c 100644 --- a/src/Paramore.Brighter/CommandProcessor.cs +++ b/src/Paramore.Brighter/CommandProcessor.cs @@ -292,7 +292,7 @@ public async Task SendAsync( var handlerChain = builder.BuildAsync(context, continueOnCapturedContext); AssertValidSendPipeline(command, handlerChain.Count()); - + await handlerChain.First().HandleAsync(command, cancellationToken) .ConfigureAwait(continueOnCapturedContext); } @@ -348,9 +348,11 @@ public void Publish(T @event, RequestContext? requestContext = null) where T { var handlerName = handleRequests.Name.ToString(); handlerSpans[handlerName] = _tracer?.CreateSpan(CommandProcessorSpanOperation.Publish, @event, span, options: _instrumentationOptions)!; - context.Span = handlerSpans[handlerName]; + if(handleRequests.Context is not null) + handleRequests.Context.Span = handlerSpans[handlerName]; handleRequests.Handle(@event); - context.Span = span; + if(handleRequests.Context is not null) + handleRequests.Context.Span = span; } catch (Exception e) { @@ -426,9 +428,11 @@ public async Task PublishAsync( foreach (var handleRequests in handlerChain) { handlerSpans[handleRequests.Name.ToString()] = _tracer?.CreateSpan(CommandProcessorSpanOperation.Publish, @event, span, options: _instrumentationOptions)!; - context.Span =handlerSpans[handleRequests.Name.ToString()]; + if(handleRequests.Context is not null) + handleRequests.Context.Span = handlerSpans[handleRequests.Name.ToString()]; tasks.Add(handleRequests.HandleAsync(@event, cancellationToken)); - context.Span = span; + if(handleRequests.Context is not null) + handleRequests.Context.Span = span; } await Task.WhenAll(tasks).ConfigureAwait(continueOnCapturedContext); diff --git a/src/Paramore.Brighter/PipelineBuilder.cs b/src/Paramore.Brighter/PipelineBuilder.cs index 0ead46d96c..3e9abf392a 100644 --- a/src/Paramore.Brighter/PipelineBuilder.cs +++ b/src/Paramore.Brighter/PipelineBuilder.cs @@ -87,10 +87,13 @@ public Pipelines Build(IRequestContext requestContext) observers.Each(observer => { + var context = observers.Count() == 1 ? requestContext : requestContext.CreateCopy(); var instanceScope = GetSyncInstanceScope(); var handler = (RequestHandler)_handlerFactorySync.Create(observer, instanceScope); - var pipeline = BuildPipeline(handler, requestContext.CreateCopy(), instanceScope); + var pipeline = BuildPipeline(handler, context, instanceScope); pipeline.AddToLifetime(instanceScope); + + pipelines.Add(pipeline); }); return pipelines; @@ -174,11 +177,14 @@ public AsyncPipelines BuildAsync(IRequestContext requestContext, bool observers.Each(observer => { + var context = observers.Count() == 1 ? requestContext : requestContext.CreateCopy(); var instanceScope = GetAsyncInstanceScope(); var handler = (RequestHandlerAsync)_asyncHandlerFactory.Create(observer, instanceScope); - var pipeline = BuildAsyncPipeline(handler, requestContext.CreateCopy(), instanceScope, + var pipeline = BuildAsyncPipeline(handler, context, instanceScope, continueOnCapturedContext); pipeline.AddToLifetime(instanceScope); + + pipelines.Add(pipeline); }); return pipelines; diff --git a/src/Paramore.Brighter/RequestContext.cs b/src/Paramore.Brighter/RequestContext.cs index 1cc550446a..60d374bcd5 100644 --- a/src/Paramore.Brighter/RequestContext.cs +++ b/src/Paramore.Brighter/RequestContext.cs @@ -41,6 +41,13 @@ public class RequestContext : IRequestContext { private readonly ConcurrentDictionary _spans = new(); + public RequestContext() { } + + private RequestContext(ConcurrentDictionary bag) + { + Bag = bag; + } + /// /// Gets the bag. /// @@ -57,7 +64,7 @@ public class RequestContext : IRequestContext /// /// New Instance of the message public IRequestContext CreateCopy() - => new RequestContext + => new RequestContext(Bag) { Span = Span, Policies = Policies, diff --git a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/When_No_Request_Context_Is_Provided.cs b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/When_No_Request_Context_Is_Provided.cs index 9b8de7a371..35355d0604 100644 --- a/tests/Paramore.Brighter.Core.Tests/CommandProcessors/When_No_Request_Context_Is_Provided.cs +++ b/tests/Paramore.Brighter.Core.Tests/CommandProcessors/When_No_Request_Context_Is_Provided.cs @@ -86,7 +86,7 @@ public void When_No_Request_Context_Is_Provided_On_A_Publish() var commandProcessor = new CommandProcessor(registry, handlerFactory, _requestContextFactory, new PolicyRegistry()); //act - commandProcessor.Send(myEvent); + commandProcessor.Publish(myEvent); //assert _requestContextFactory.CreateWasCalled.Should().BeTrue(); @@ -108,7 +108,7 @@ public async Task When_No_Request_Context_Is_Provided_On_A_Publish_Async() var commandProcessor = new CommandProcessor(registry, handlerFactory, _requestContextFactory, new PolicyRegistry()); //act - await commandProcessor.SendAsync(myEvent); + await commandProcessor.PublishAsync(myEvent); //assert _requestContextFactory.CreateWasCalled.Should().BeTrue();