Skip to content

Sending object as IRequest throws #854

@dagophil

Description

@dagophil

Hello,
I just upgraded from MediatR 11.1.0 to 12.0.0 and found that you cannot send requests as IRequest anymore. Sending them using their concrete type, or IBaseRequest, or object still works.

Is this a bug or a feature?

Regards,
Philip

Here is a minimal reproducing example:

Program.cs:

using MediatR;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

var services = new ServiceCollection();
services.AddMediatR(o => o.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));
var sp = services.BuildServiceProvider();
var mediator = sp.GetRequiredService<IMediator>();

// Sending as MyCommand, IBaseRequest, or object works:
MyCommand cmd0 = new MyCommand() { TypeName = "MyCommand" };
await mediator.Send(cmd0);
IBaseRequest cmd1 = new MyCommand() { TypeName = "IBaseRequest" };
await mediator.Send(cmd1);
object cmd2 = new MyCommand() { TypeName = "object" };
await mediator.Send(cmd2);

// Sending as IRequest throws:
IRequest cmd3 = new MyCommand() { TypeName = "IRequest" };
await mediator.Send(cmd3);


class MyCommand : IRequest
{
    public string? TypeName { get; set; }
}

class MyCommandHandler : IRequestHandler<MyCommand>
{
    public Task Handle(MyCommand request, CancellationToken cancellationToken)
    {
        Console.WriteLine($"Handling command. Sent as {request.TypeName}");
        return Task.CompletedTask;
    }
}

Project file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="MediatR" Version="12.0.0" />
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" />
  </ItemGroup>

</Project>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions