c# - 使用接口来解析 MediatR IRequestHandler 而不是类
问题描述
我已经在 .net 5 应用程序中实现了 MediatR,并希望使用 Handler 接口解决需要的依赖项。目前我使用类名来解决如下
_mediator.Send(new GetDeviceByIMEI(imei)); // want to use interface ??
//var result = await _mediator.Send(IGetHandHeldByIMEI????);
完整的代码参考如下;
处理程序接口
public interface IGetDeviceByIMEIEventHandler
{
Task<DeviceWrapperDataView> Handle(GetDeviceByIMEI request, CancellationToken cancellationToken);
}
查询接口
public interface IGetDeviceByIMEI
{
string IMEI { get; set; }
}
询问
public class GetDeviceByIMEI: IRequest<DeviceWrapperDataView>
{
public string IMEI { get; set; }
public GetDeviceByIMEI(string imei)
{
this.IMEI = imei;
}
}
处理程序
public class GetDeviceByIMEIEventHandler : IRequestHandler<GetDeviceByIMEI, DeviceWrapperDataView>, IGetDeviceByIMEIEventHandler
{
private readonly IDeviceEntity _DeviceEntity;
public GetDeviceByIMEIEventHandler(IDeviceEntity DeviceEntity)
{
_DeviceEntity = DeviceEntity;
}
public async Task<DeviceWrapperDataView> Handle(GetDeviceByIMEI request, CancellationToken cancellationToken)
{
// code to get data
return DeviceOutput;
}
}
API 控制器
private readonly IMediator _mediator;
public DeviceController(
IMediator mediator)
{
_mediator = mediator;
}
[HttpGet()]
public async Task<IActionResult> GetDeviceByIMEI(string imei)
{
Var result = await _mediator.Send(new GetDeviceByIMEI(imei));
// want to use
}
解决方案
为此,您必须在容器中使用每个继承查询接口的类注册处理程序。
例如,您提供的代码。
public interface IGetDeviceByIMEI : IRequest<DeviceWrapperDataView>
{
string IMEI { get; set; }
}
public class GetDeviceByIMEI: IGetDeviceByIMEI
{
public string IMEI { get; set; }
public GetDeviceByIMEI(string imei)
{
this.IMEI = imei;
}
}
public class AnotherGetDeviceByIMEI: IGetDeviceByIMEI
{
public string IMEI { get; set; }
public GetDeviceByIMEI(string imei)
{
this.IMEI = imei;
}
}
public class GetDeviceByIMEIEventHandler : IRequestHandler<IGetDeviceByIMEI, DeviceWrapperDataView>, IGetDeviceByIMEIEventHandler
{
private readonly IDeviceEntity _DeviceEntity;
public GetDeviceByIMEIEventHandler(IDeviceEntity DeviceEntity)
{
_DeviceEntity = DeviceEntity;
}
public async Task<DeviceWrapperDataView> Handle(IGetDeviceByIMEI request, CancellationToken cancellationToken)
{
// code to get data
return DeviceOutput;
}
}
完成此操作后,您必须在每个用例的容器中注册处理程序。
例如,在 .Net Core 中,您可以使用 StartUp 类中的 serviceCollection 来完成。
serviceCollection.AddTransient<IRequestHandler<GetDeviceByIMEI, DeviceWrapperDataView>, GetDeviceByIMEIEventHandler >();
serviceCollection.AddTransient<IRequestHandler<AnotherGetDeviceByIMEI, DeviceWrapperDataView>, GetDeviceByIMEIEventHandler >();
问候。
推荐阅读
- python - pymongo - 搜索包含 $ 和运算符不区分大小写的文档的集合
- powershell - 在 Youtube 上使用 powershell 获取推荐视频
- c++ - 如何使用 strtok() 函数改进搜索?
- android - 未经验证的用户可以登录到应用程序。如何预防?
- oracle - 如何在 Oracle Enterprise Manager (OEM) 中获取函数的 DDL/源代码
- mysql - 从两个单独的列表创建 erlang 记录
- python - python 3 TypeError:if语句中的'int'和'str'实例之间不支持'>'
- symfony - 在 Symfony 4 中查找模板的所有路由
- xaml - UWP:如何根据内容调整窗口大小?
- php - PHP 的输出作为占位符