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

如何在ServiceStack中正确配置MediatR解决MemberAccessException错误

错误根因

报错是因为传入Mediator构造函数的服务工厂委托逻辑错误,当MediatR需要解析IRequestHandler、INotificationHandler这类抽象服务实例时,你直接调用x.CreateInstance()尝试实例化接口/抽象类,自然触发Cannot create an abstract class异常。


可行配置方案

你需要将MediatR的服务解析绑定到ServiceStack的FunQ容器,同时提前注册所有你项目中实现的MediatR处理类,具体配置代码如下:

public override void Configure(Container container)
{
    SetConfig(new HostConfig { DebugMode = true });

    // 1. 批量注册项目中所有MediatR处理类
    // 请把typeof(MyHandler)替换为你项目中Handler所在程序集的任意一个类,用于触发程序集扫描
    var handlerTypes = typeof(MyHandler).Assembly.GetTypes()
        .Where(t => t.GetInterfaces().Any(i => 
            i.IsGenericType && 
            (i.GetGenericTypeDefinition() == typeof(IRequestHandler<>) || 
             i.GetGenericTypeDefinition() == typeof(IRequestHandler<,>) ||
             i.GetGenericTypeDefinition() == typeof(INotificationHandler<>))));
    
    foreach (var handlerType in handlerTypes)
    {
        var handlerInterface = handlerType.GetInterfaces().First(i => 
            i.IsGenericType && 
            (i.GetGenericTypeDefinition() == typeof(IRequestHandler<>) || 
             i.GetGenericTypeDefinition() == typeof(IRequestHandler<,>) ||
             i.GetGenericTypeDefinition() == typeof(INotificationHandler<>)));
        container.Register(handlerInterface, handlerType);
    }

    // 2. 绑定MediatR服务工厂到ServiceStack容器
    var mediator = new Mediator(serviceType =>
    {
        return container.TryResolve(serviceType);
    });
    container.Register<IMediator>(mediator);

    // 其他业务服务注册
    container.Register(c => new MyService(c.Resolve<IMediator>()));
}

注意事项

  • 如果需要支持同一个请求对应多个通知Handler,注册时改用container.RegisterAutoWiredAs(handlerType, handlerInterface)即可
  • 如果用到MediatR的管道中间件,只需在扫描逻辑中新增IPipelineBehavior<,>的泛型匹配规则,完成批量注册即可
  • 该配置完全兼容你当前使用的.NET Framework 4.5、ServiceStack v5.10.4、MediatR v5.1.0版本,无需升级依赖

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 04:00:00