MediatR
MediatR copied to clipboard
How to do generic handler using entities?
I can use like this. It works when I call _mediatr.Send(new Query.Get()).
public class Query
{
public class Get : Product, IRequest<Product>
{
public class Handler : IRequestHandler<Get, Product>
{
private readonly IProductRepository _product;
public Handler(IProductRepository product)
{
_product = product;
}
public Task<Product> Handle(Get request, CancellationToken cancellationToken)
{
var product = _product.GetAll(request);
return Task.FromResult(product);
}
}
}
}
But i cant get generic handler working.
public class SharedQuery
{
public class Get<T> : *T*, IRequest<T> where T : class
{
public class Handler : IRequestHandler<Get<T>, T>
{
private readonly IBaseRepository<T> _repo;
public Handler(IBaseRepository<T> repo)
{
_repo = repo;
}
public Task<T> Handle(Get<T> request, CancellationToken cancellationToken)
{
var data = _repo.GetAll(*request*);
return Task.FromResult(data);
}
}
}
}
Got 2 errors. I added * between the letter/word which is error.
- T = Error CS0689 Cannot derive from 'T' because it is a type parameter
- request = Error CS1503 Argument 1: cannot convert from 'Web.Handlers.SharedQuery.Get<T>' to 'T'
How to get generic handler working?
there are a couple of ways to do it.. The easiest way in my opinion is using AutoFac... But with some extra code (defining concrete handler types that derive from an abstract generic base handler) You can use the default DI container.
https://github.com/jbogard/MediatR/issues/635#issuecomment-870085628 https://github.com/jbogard/MediatR/issues/521#issuecomment-897131719