Search code examples
c#ninjectmediatr

Is it possible to handle one query but with different handlers using mediatR?


I am using ninject + mediatR. I have class that inherits methods from different interfaces:

class Query : IRequest<IReadOnlyList<QueryResult>>, interfaceName1, interfaceName2
{
    public string methodFromFirstInterface();
    public string methodFromSecondInterface();
}

and I would like to use mediatR to work with this query. Can I do something like this?

public class QueryHandler : IRequestHandler<Query, IReadOnlyList<QueryResult>>
{
    //first handler 
    public IReadOnlyList<QueryResult> Handle(Query message)
    {
        //something
    }
    //second handler 
    public IReadOnlyList<QweReportModel> Handle(interfaceName1 message)
    {
        message.methodFromFirstInterface();
    }

    //third handler 
    public IReadOnlyList<QweReportModel> Handle(interfaceName2 message)
    {
        message.methodFromSecondInterface();
    }
}

Is it possible somehow to send a query with mediatR to call second or third handler, not the first?


Solution

  • This is not possible, requests are dispatched to handlers by concrete request type. You would have to create derrived type for each request:

    public class Query1 : Query, interfaceName1, IRequest<IReadOnlyList<QweReportModel>>
    public class Query2 : Query, interfaceName2, IRequest<IReadOnlyList<QweReportModel>>
    

    Than your handler would look like:

    public class QueryHandler : 
        IRequestHandler<Query, IReadOnlyList<QueryResult>>,
        IRequestHandler<Query1, IReadOnlyList<QweReportModel>>,
        IRequestHandler<Query2, IReadOnlyList<QweReportModel>>
    

    and dispatch:

    mediator.Send<IReadOnlyList<QweReportModel>>(new Query1());
    mediator.Send<IReadOnlyList<QweReportModel>>(new Query2());