From 95d164e3fd383c6aac5e7b288c3398bd2c3c8862 Mon Sep 17 00:00:00 2001 From: Remco Ros Date: Wed, 15 Feb 2023 16:54:55 +0100 Subject: [PATCH 1/2] Use actual request type --- src/MediatR/Mediator.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/MediatR/Mediator.cs b/src/MediatR/Mediator.cs index 58b3f808..adde975e 100644 --- a/src/MediatR/Mediator.cs +++ b/src/MediatR/Mediator.cs @@ -63,7 +63,7 @@ public Task Send(TRequest request, CancellationToken cancellationToken throw new ArgumentNullException(nameof(request)); } - var requestType = typeof(TRequest); + var requestType = request.GetType(); var handler = (RequestHandlerWrapper)_requestHandlers.GetOrAdd(requestType, static t => (RequestHandlerBase)(Activator.CreateInstance(typeof(RequestHandlerWrapperImpl<>).MakeGenericType(t)) @@ -207,4 +207,4 @@ public IAsyncEnumerable CreateStream(IStreamRequest Date: Wed, 15 Feb 2023 17:21:04 +0100 Subject: [PATCH 2/2] Add test --- test/MediatR.Tests/PublishTests.cs | 5 +++-- test/MediatR.Tests/SendTests.cs | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/test/MediatR.Tests/PublishTests.cs b/test/MediatR.Tests/PublishTests.cs index ce33dc50..a9ca5873 100644 --- a/test/MediatR.Tests/PublishTests.cs +++ b/test/MediatR.Tests/PublishTests.cs @@ -215,8 +215,9 @@ public async Task Should_resolve_handlers_given_interface() var mediator = container.GetInstance(); - INotification notification = new Ping { Message = "Ping" }; - await mediator.Publish(notification); + // wrap notifications in an array, so this test won't break on a 'replace with var' refactoring + var notifications = new INotification[] { new Ping { Message = "Ping" } }; + await mediator.Publish(notifications[0]); var result = builder.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None); result.ShouldContain("Ping Pong"); diff --git a/test/MediatR.Tests/SendTests.cs b/test/MediatR.Tests/SendTests.cs index 466ba72b..7ca41fe7 100644 --- a/test/MediatR.Tests/SendTests.cs +++ b/test/MediatR.Tests/SendTests.cs @@ -175,6 +175,31 @@ public async Task Should_resolve_main_handler_by_specific_interface() response.Message.ShouldBe("Ping Pong"); } + [Fact] + public async Task Should_resolve_main_handler_by_given_interface() + { + var dependency = new Dependency(); + var container = new Container(cfg => + { + cfg.Scan(scanner => + { + scanner.AssemblyContainingType(typeof(PublishTests)); + scanner.IncludeNamespaceContainingType(); + scanner.WithDefaultConventions(); + scanner.AddAllTypesOf(typeof(IRequestHandler<>)); + }); + cfg.ForSingletonOf().Use(dependency); + cfg.For().Use(); + }); + + var mediator = container.GetInstance(); + + // wrap requests in an array, so this test won't break on a 'replace with var' refactoring + var requests = new IRequest[] { new VoidPing() }; + await mediator.Send(requests[0]); + + dependency.Called.ShouldBeTrue(); + } [Fact] public async Task Should_raise_execption_on_null_request()