'IServiceCollection' 不包含 'AddMediatR' 的定义并且没有可访问的扩展方法 'AddMediatR' 接受

'IServiceCollection' does not contain a definition for 'AddMediatR' and no accessible extension method 'AddMediatR' accepting

我在 Program.cs 中使用 .NET 6:

builder.Services.AddMediatR(Assembly.GetExecutingAssembly());

I get: 'IServiceCollection' does not contain a definition for 'AddMediatR' and no accessible extension method 'AddMediatR' accepting a first argument of type 'IServiceCollection' could be found' (are you missing a using directive or an assembly reference?)

为什么?

首先你必须

Install-Package MediatR

然后在 IServiceCollection 中访问必须

Install-Package MediatR.Extensions.Microsoft.DependencyInjection