.NET 8 反射注册 DI 时泛型 Task<> 服务启动失败
结论
Task<>、泛型方法以及 DI 对泛型的支持都没有问题。异常的根源是 Assembly.GetTypes() 也会返回编译器生成的类型。
编译 Repository.Calculate<T>() 时,编译器会生成一个异步状态机类型,名称类似:
Repository+<Calculate>d__0<T>
这个类型实现了 IAsyncStateMachine,而且只实现了这一个接口,因而被现有代码误注册为:
services.AddScoped(
typeof(IAsyncStateMachine),
typeof(Repository.<Calculate>d__0<>));
DI 容器无法像实例化普通服务一样实例化这个开放的编译器内部类型,所以应用会在启动时抛出异常。
修复时应排除带有 CompilerGeneratedAttribute 的类型。这样可以过滤掉编译器生成的辅助类型,同时保留合法的泛型服务。
最小修改方案
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Server;
public static class AddServices
{
public static IServiceCollection AddRepositories(
this IServiceCollection services)
{
Assembly.Load("Services")
.GetTypes()
.Where(type =>
!type.IsAbstract &&
!type.IsInterface &&
!type.IsDefined(
typeof(CompilerGeneratedAttribute),
inherit: false))
.Select(type => new
{
AssignedType = type,
ServiceTypes = type.GetInterfaces()
})
.ToList()
.ForEach(typeToRegister =>
{
if (typeToRegister.ServiceTypes.Length != 1)
{
return;
}
services.AddScoped(
typeToRegister.ServiceTypes[0],
typeToRegister.AssignedType);
});
return services;
}
}
这项过滤只排除编译器生成的辅助类型,不会把泛型服务类一起排除。
Repository 本身不是泛型类型,只是包含一个泛型方法:
Task<decimal> Calculate<T>(List<T> list)
过滤异步状态机后,正常的注册关系仍然是:
IRepository -> Repository
控制器调用 Calculate<Person>() 或 Calculate<Company>() 时,也不需要为每个泛型参数单独注册服务。
原来的条件为什么会命中异步状态机
原来的筛选条件是:
!type.IsAbstract && !type.IsInterface
编译器生成的异步状态机同样满足这两个条件。此类状态机通常有以下特征:
- 它是嵌套的非公开类型;
- 它实现
System.Runtime.CompilerServices.IAsyncStateMachine; - 它带有
CompilerGeneratedAttribute; - 如果异步方法是泛型方法,状态机类型也会包含泛型参数。
接下来的判断又让它通过了注册检查:
if (typeToRegister.serviceTypes.Length != 1)
return;
状态机恰好只实现 IAsyncStateMachine,于是代码将它当作合法服务注册。异常中出现的实现类型和服务类型就是这样产生的:
Repository+d__0`1[T]
IAsyncStateMachine
支持开放泛型服务
下面这种定义才是真正的泛型依赖:
public interface IRepository<T>
{
}
public class Repository<T> : IRepository<T>
{
}
Microsoft DI 通常需要按照泛型类型定义注册:
services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
如果自动扫描还要覆盖这种场景,可以先把开放泛型接口转换成泛型类型定义,再进行注册:
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Server;
public static class AddServices
{
public static IServiceCollection AddRepositories(
this IServiceCollection services)
{
var assembly = Assembly.Load("Services");
var implementationTypes = assembly
.GetTypes()
.Where(type =>
!type.IsAbstract &&
!type.IsInterface &&
!type.IsDefined(
typeof(CompilerGeneratedAttribute),
inherit: false));
foreach (var implementationType in implementationTypes)
{
var serviceTypes = implementationType.GetInterfaces();
if (serviceTypes.Length != 1)
{
continue;
}
var serviceType = serviceTypes[0];
if (implementationType.IsGenericTypeDefinition)
{
if (!serviceType.IsGenericType ||
!serviceType.ContainsGenericParameters)
{
continue;
}
var serviceTypeDefinition =
serviceType.GetGenericTypeDefinition();
if (serviceTypeDefinition.GetGenericArguments().Length !=
implementationType.GetGenericArguments().Length)
{
continue;
}
services.AddScoped(
serviceTypeDefinition,
implementationType);
}
else
{
if (implementationType.ContainsGenericParameters ||
serviceType.ContainsGenericParameters)
{
continue;
}
services.AddScoped(serviceType, implementationType);
}
}
return services;
}
}
这段代码可以处理两种常见的注册关系:
IRepository -> Repository
IRepository<> -> Repository<>
开放泛型接口和实现之间必须存在 DI 容器可以正确闭合的对应关系,例如 IRepository<T> 对应 Repository<T>。参数数量相同只是最基本的检查。遇到泛型参数重排、部分闭合或特殊映射时,通常需要显式注册。
注意事项
不建议把下面的条件作为主要修复方式:
!type.IsGenericType
它能排除当前的泛型异步状态机,也会把 Repository<T> 这类合法的开放泛型服务排除掉。
还可以使用 IsPublic、IsNestedPublic 或 DeclaringType 过滤非公开嵌套类型,但这样也会排除用户编写的内部类或嵌套服务。对于当前问题,检查 CompilerGeneratedAttribute 更准确。
现有代码仍然只注册恰好实现一个接口的类型。因此,同时实现业务接口和 IDisposable、IAsyncDisposable 等接口的服务会被跳过。如果项目中出现这种情况,可以明确筛选业务接口,或使用自定义标记 Attribute,避免只根据接口数量判断。
备注:内容仅供参考。
