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

Azure Function v4中使用MediatR遇依赖注册错误的解决方法

修复Azure Function v4 + MediatR v12.1.1 + Autofac的请求处理程序未注册错误

问题根源

你在Azure Function项目的Startup.cs中仅注册了当前项目的程序集,但MediatR的请求(IRequest实现)和处理程序(IRequestHandler<TRequest, TResult>实现)都在独立的Services类库项目中,导致Autofac无法扫描到这些类型,从而抛出未注册服务的错误。

修复步骤

  1. 确认类库引用
    确保Azure Function项目已正确添加对Services类库项目的引用,保证编译后能加载到该类库的程序集。

  2. 修改Autofac注册逻辑,包含Services类库程序集
    在Startup的ConfigureContainer方法中,调整MediatR的注册代码,将Services类库的程序集纳入扫描范围。可以通过类库中的任意类型获取其程序集,示例代码如下:

    using Autofac;
    using MediatR;
    using Services; // 引入Services类库的命名空间
    using System.Reflection;
    
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            // 其他服务配置
        }
    
        public override void ConfigureContainer(ContainerBuilder builder)
        {
            // 获取Services类库的程序集(替换为你项目中实际的请求/处理程序类型)
            var servicesAssembly = typeof(YourSampleRequest).Assembly;
            // 当前Function项目的程序集
            var functionAssembly = Assembly.GetExecutingAssembly();
    
            // 注册MediatR核心组件及所有实现类
            builder.RegisterAssemblyTypes(typeof(IMediator).Assembly, functionAssembly, servicesAssembly)
                   .AsImplementedInterfaces();
    
            // 显式注册所有IRequestHandler实现(包含Services类库中的类型)
            builder.RegisterAssemblyTypes(servicesAssembly, functionAssembly)
                   .AsClosedTypesOf(typeof(IRequestHandler<,>));
    
            // 注册MediatR所需的服务工厂
            builder.Register<ServiceFactory>(ctx =>
            {
                var componentContext = ctx.Resolve<IComponentContext>();
                return type => componentContext.Resolve(type);
            });
    
            builder.RegisterType<Mediator>()
                   .As<IMediator>()
                   .InstancePerLifetimeScope();
        }
    }
    
  3. 使用MediatR Autofac扩展简化注册(可选)
    如果你安装了MediatR.Extensions.Autofac.DependencyInjection包(版本需与MediatR v12.1.1兼容),可以用更简洁的方式完成注册:

    builder.AddMediatR(cfg =>
    {
        cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
        cfg.RegisterServicesFromAssembly(typeof(YourSampleRequest).Assembly);
    });
    

验证要点

  • 确认YourSampleRequest或替换的类型确实属于Services类库项目,确保程序集获取正确。
  • 检查所有IRequestHandler<,>实现类的访问修饰符为public,避免Autofac无法扫描到私有/内部类型。

内容的提问来源于stack exchange,提问作者Ilya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 01:12:50