Hey I try to cast my object to interface which this object should implements. But during executing code I have following error:
Unable to cast object of type GetTreeHandler to IQueryHandler, IQuery<Tree>.
Why? Everything seems to be ok.
Any idea without using dynamic?
QueryDispatcher
public async Task<TResult> ExecuteAsync<TResult>(IQuery<TResult> query)
{
if (query == null)
{
throw new ArgumentNullException("Query can not be null.");
}
var handlerType = typeof (IQueryHandler<,>).MakeGenericType(query.GetType(), typeof (TResult));
var handler = _context.Resolve(handlerType);
IQueryHandler<IQuery<TResult>, TResult> castedHandler = (IQueryHandler<IQuery<TResult>, TResult>) handler;
return (TResult) await castedHandler.ExecuteAsync(query);
}
GetTreeHandler
public class GetTreeHandler : IQueryHandler<GetTree, Tree>
{
private readonly ProductContext _context;
public string Name { get; set; }
public GetTreeHandler(ProductContext context)
{
_context = context;
}
public async Task<Tree> ExecuteAsync(GetTree query)
=> await Task.FromResult(
_context.Trees.FirstOrDefault(x => x.Id == query.Id)
);
}
EDIT
My current solution(partially works):
public async Task<TResult> ExecuteAsync<TResult>(IQuery query) where TResult : class
{
if (query == null)
{
throw new ArgumentNullException("Query can not be null.");
}
var handlerType = typeof (IQueryHandler<,>).MakeGenericType(query.GetType(), typeof (TResult));
var handler = _context.Resolve(handlerType);
return await (Task<TResult>)
handler.GetType()
.GetMethod("ExecuteAsync")
.Invoke(handler, new object[]{query});
}
Why partially? Eg. handlers:
Doesn't work:
public class GetIndexesHandler : IQueryHandler<GetIndexes, IEnumerable<AssocIndexDto>>
Works:
public class GetIndexesHandler : IQueryHandler<GetIndexes,AssocIndexDto>
As you can see these two classes implements the same interface but with different second parameter type.
The problem is that Resolve method cannot find the registered service, but if I try to debug this code, I can see that the wanted service is registed correctly, but it can't be found.
Have you any idea how to solve it?