.net 方法“Handle”无法从接口“MediatR.IRequestHandler”中实现方法

lymnna71  于 2023-06-25  发布在  .NET
关注(0)|答案(1)|浏览(171)

我试图创建一个“创建”API端点在.NET以下的教程.下面的代码应该工作,但它不是。
获取此错误:

error CS0738: 'Create.Handler' does not implement interface member 'IRequestHandler<Create.Command>.Handle
(Create.Command, CancellationToken)'. 'Create.Handler.Handle(Create.Command, CancellationToken)' cannot implement 'IRequestHandler<Create.Command>.Handle(Create.Command, CancellationToken)' because i
t does not have the matching return type of 'Task'
using Domain;
using MediatR;
using Persistence;

namespace Application.Activities;

public class Create
{
    public class Command : IRequest
    {
        public Activity Activity { get; set; }
    }

    public class Handler : IRequestHandler<Command>
    {
        private readonly DataContext _context;

        public Handler(DataContext context)
        {
            _context = context;
        }

        public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
        {
            _context.Activities.Add(request.Activity);
            await _context.SaveChangesAsync();
            return Unit.Value;
        }
    }
}
uplii1fm

uplii1fm1#

显示此错误是因为您没有显式地告诉MediatR处理程序和命令的返回类型。它取决于Unit.Value变量的数据类型。假设它是一个字符串,试试这个:

public class Create
{
  public class Command : IRequest<string>
 {
    public Activity Activity { get; set; }
 }

public class Handler : IRequestHandler<Command, string>
{
    private readonly DataContext _context;

    public Handler(DataContext context)
    {
        _context = context;
    }

    public async Task<string> Handle(Command request, CancellationToken cancellationToken)
    {
        _context.Activities.Add(request.Activity);
        await _context.SaveChangesAsync();
        return Unit.Value;
    }
  }
}

相关问题