【发布时间】:2019-12-21 13:58:35
【问题描述】:
我正在使用 Mediatr 开发 ASP.NET Core 2.2 Web API 应用程序。
我有一个看起来像 -
public class MyQueryHandler<T> : IRequestHanlder<MyQuery<T>, IQueryable<T>>
{
public Task<IQueryable<T>> Handle(MyQuery<T> myquery, CancellationToken cancellationToken)
{
//perform query
IQueryable<T> models = someDatabaseQuery.ProjectTo<T>();
}
}
这是查询 -
public class MyQuery<T> : IRequest<IQueryable<T>>
{
//some properties
}
当我尝试提出这样的请求时 -
var result = await _mediator.Send(new MyQuery<SomeModel> {/* set the properties on the query */})
我得到一个例外 -
An unhandled exception occurred while processing the request.
InvalidOperationException: Handler was not found for request of type MediatR.IRequestHandler`2[MyQuery`1[SomeModel],System.Linq.IQueryable`1[SomeModel]]. Register your handlers with the container. See the samples in GitHub for examples.
我花了好几个小时尝试了很多东西,但都没有奏效。按照 Mediator github repo 中提供的示例,我什至厌倦了在服务集合旁边使用 Autofac。
【问题讨论】:
-
我认为每个 Query 对象都应该有一个像
Dtos这样的扁平结构,所以它的处理程序可以很容易地在运行时注册。如果您想创建一些通用查询处理程序,为什么不只使用 Behaviors? -
你能告诉我
MyQuery<T>的目标是什么 -
在处理程序中,我使用自动映射器投影来限制从相关数据库表中查询的内容。
让调用者告诉查询,然后处理程序需要的数据形状。 -
我更新了我的答案。这是您问题的答案还是您想要实现不同的目标?如果没有,请给我更多详细信息,以便我可以尝试提供帮助。我花了几个小时在这个库上苦苦挣扎,所以我知道你的痛苦:D
-
我对我的具体问题有一个解决方案,我会尽快写一个答案。
标签: c# covariance contravariance mediator mediatr