首页 > 解决方案 > 使用接口来解析 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 
  }

标签: c#cqrs.net-5mediatr

解决方案


为此,您必须在容器中使用每个继承查询接口的类注册处理程序。

例如,您提供的代码。

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 >();

问候。


推荐阅读