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
相关产品推荐
相关产品推荐

