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

MediatR中注册带泛型子类型的依赖:解决CS7003编译错误

解决CS7003错误:正确注册泛型通知处理程序

你遇到的CS7003错误是因为C#不允许直接书写嵌套的未绑定泛型类型(比如INotificationHandler<GenericEvent<>>)。要正确注册这种嵌套泛型的处理程序,需要通过Type.MakeGenericType方法构造合法的开放泛型服务类型。

修改后的注册代码如下:

public static class RegistrationTest
{
    public static void Register(IServiceCollection services)
    {
        // 构造开放泛型服务类型:INotificationHandler<GenericEvent<T>>
        var serviceType = typeof(INotificationHandler<>).MakeGenericType(typeof(GenericEvent<>));
        // 注册对应的开放泛型实现类型
        services.AddTransient(serviceType, typeof(GenericEventHandler<>));
    }
}

原理说明

  • typeof(INotificationHandler<>)获取的是INotificationHandler<T>的开放泛型类型
  • 调用MakeGenericType(typeof(GenericEvent<>))后,会生成INotificationHandler<GenericEvent<T>>的开放泛型类型,这正是GenericEventHandler<T>所实现的接口类型
  • .NET原生DI容器支持开放泛型注册,当后续请求具体类型(比如INotificationHandler<GenericEvent<int>>)时,容器会自动创建对应的GenericEventHandler<int>实例

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:55:25