有一个同步处理程序和一个异步处理程序

Have a synchronous handler and an asynchronous handler

请看下面的同步代码:

public class PersonHandler : IRequestHandler<Person, Person>
    {
        public Task<Person> Handle(Person request, CancellationToken cancellationToken)
        {
            request.ID = 1;
            request.Name = "Brian";
            request.Age = 53;
            return Task.FromResult(request);
        }
    }

调用代码如下:

var response2 = mediator.Send(new Person());

这按预期工作。请看下面的异步代码:

public class PersonHandlerAsync : IRequestHandler<Person, Person>
    {
        public async Task<Person> Handle(Person request, CancellationToken cancellationToken)
        {
            request.ID = 1;
            request.Name = "Brian";
            request.Age = 53;
            var result = await Task.FromResult(request);
            await Task.Delay(30000);
            return result;
        }
    }

调用代码如下:

var response = Task.Run(() => mediator.Send(new Person()));

此代码按预期工作。

是否可以为同一个 class(人员)设置两个处理程序,即一个同步处理程序和另一个异步处理程序?如果我将两个处理程序 classes 都放在我的代码中,那么 mediator.send 行,即 mediator.Send(new Person());Task.Run(() => mediator.Send(new Person())); 都会调用同步方法。

如何告诉 mediatr 使用哪个处理程序 class?即用于同步调用的 PersonH​​andler 和用于异步调用的 PersonH​​andlerAsync。

你不能按照你指定的方式去做。

Declare whatever flavor of handler you need - sync, async or cancellable async. From the IMediator side, the interface is async-only, designed for modern hosts.

但是,一种解决方法是创建 PersonRequestPersonRequestAsync class,继承自 Person class:

public class Person
{
    public int Id {get; set;}
    public string Name {get; set;}
    public int Age {get; set;}
}

//sync request
public class PersonRequest : Person, IRequest<Person>
{ }

//async request
public class PersonRequestAsync : Person, IRequest<Person>
{ }

然后,您的处理程序可能看起来像这样:

public class PersonHandler : IRequestHandler<PersonRequest, Person>
{
    public Task<Person> Handle(Person request, CancellationToken cancellationToken)
    {
        request.ID = 1;
        request.Name = "Brian";
        request.Age = 53;
        return Task.FromResult(request);
    }
}

您的 async 处理程序如下:

public class PersonHandlerAsync : IRequestHandler<PersonRequestAsync, Person>
{
    public async Task<Person> Handle(PersonRequestAsync request, CancellationToken cancellationToken)
    {
        request.ID = 1;
        request.Name = "Brian";
        request.Age = 53;

        //not sure what this is? Hopefully it's just here for demo purposes!
        var result = await Task.FromResult(request);

        await Task.Delay(30000);

        return result;
    }
}

这有效地将 PersonRequestAsyncPersonHandlerAsync

联系起来