You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure Function v4运行时出现MediatR IRequestHandler服务未找到错误

问题分析

运行时出现No service for type 'MediatR.IRequestHandler'错误的核心原因是:你的MediatR服务注册仅扫描了Azure Function项目自身的程序集,而处理命令的UploadImageHandler位于类库项目中,导致依赖注入容器无法找到该处理器。

解决方案

1. 修改MediatR注册逻辑,包含类库程序集

在Azure Function项目的Startup.cs中,更新MediatR的注册代码,同时包含类库项目的程序集。可以通过类库中的任意类型(比如UploadImageCommand)来获取其所在程序集:

using MediatR;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using System.Reflection;

[assembly: FunctionsStartup(typeof(YourFunctionNamespace.Startup))]
namespace YourFunctionNamespace
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddMediatR(cfg => 
            {
                // 注册当前Function项目+类库项目的所有MediatR相关类型
                cfg.RegisterServicesFromAssemblies(
                    Assembly.GetExecutingAssembly(),
                    typeof(UploadImageCommand).Assembly // 类库项目的程序集
                );
            });

            // 别忘了注册IMyBlobService的实现到DI容器
            builder.Services.AddScoped<IMyBlobService, MyBlobService>();
        }
    }
}

2. 确保NuGet包版本一致

检查Azure Function项目和类库项目的MediatR相关NuGet包版本完全匹配,包括:

  • MediatR
  • MediatR.Extensions.Microsoft.DependencyInjection

版本不匹配可能导致类型加载或注册失败。

3. 验证处理器的访问权限与依赖

  • 确保UploadImageHandler是public修饰的,否则DI容器无法发现它;
  • 确认IMyBlobService已经正确注册到依赖注入容器中,否则即使找到处理器,也会因缺少依赖抛出其他错误。

4. 调试验证注册结果(可选)

可以在Startup中添加调试代码,确认处理器是否被成功注册:

var registeredHandlers = builder.Services
    .Where(s => s.ServiceType.IsGenericType 
                && s.ServiceType.GetGenericTypeDefinition() == typeof(IRequestHandler<,>))
    .ToList();
// 在调试模式下查看registeredHandlers列表,确认包含UploadImageHandler

内容的提问来源于stack exchange,提问作者Patrick de Jong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 13:32:13