What's wrong with this Generic Type constraints in c#?

211 Views Asked by At

I'm working on a c# application that uses MediatR packet. I'm pretty new to c# and I'm struggling to understand what's wrong with the type constraints I've written.

Please, I've not added any specific code for the classes/interfaces since the problem can be reproduced with totally empty classes/interfaces (see the example on dotnetfiddle)

This is the basic code from MediatR needed to understand my case:

public interface IRequest<out TResponse>{ ... }

public interface IRequestHandler<in TRequest, TResponse>
    where TRequest : IRequest<TResponse>{ ... }

Here is my code:

// an interface common to all the response DTOs
public interface IResponseDto
{ ... }

// an interface for a repository of items
public interface IItemRepository
{ ... }

// This is a class that describes a response.
public class Response<TResponseDto>
    where TResponseDto : class, IResponseDto
    { ... }


// This is a base class for requests.
// I want the derived class to implement IRequest interface (from MediatR)
public abstract class BaseRequest<TResponseDto> : IRequest<Response<TResponseDto>>
    where TResponseDto : class, IResponseDto
    { ... }


// This is a base class for request handlers
// I want the derived class to implement IRequestHandler interface (from MediatR)
public abstract class BaseRequestHandler<TRepository, TRequest> :
    IRequestHandler<TRequest, Response<IResponseDto>>
    where TRequest : class, IRequest<Response<IResponseDto>>
    { ... }

Now, I tried to use the classes above in this way but I've got an error.

public class ReadItemResponseDto : IResponseDto
{ ... }

public class ReadItemQuery : BaseRequest<ReadItemResponseDto>
{ ... }

// Here I've got the error
public class ReadItemQueryHanlder : BaseRequestHandler<IItemRepository, ReadItemQuery>
{ ... }

The error says I cannot use the parameter ReadItemQuery as parameter of type TRequest because there is no way to convert from ReadItemQuery to MediatR.IRequest<Response<IResponseDto>>

I can't understand the cause of the error. Infact my ReadItemQuery class derives from BaseRequest<TResponseDto> that in turn implements IRequest<Response<TResponseDto>> with TResponseDto = ReadItemResponseDto.

0

There are 0 best solutions below