在ASP.NET Core 1.1.2 web项目中,这取决于Microsoft.Extensions.DependencyInjection 1.1.1,我试图注册一个通用的FluentValidation验证器与它的实现和它的接口。在运行时,主机建设过程中,我得到了以下异常:使用ASP.NET Core注册部分关闭的泛型类型Microsoft.Extensions.DependencyInjection
An unhandled exception of type 'System.ArgumentException' occurred in Microsoft.Extensions.DependencyInjection.dll
Cannot instantiate implementation type 'MyProj.Shared.Api.WithUserCommandValidator`1[T]' for service type 'FluentValidation.IValidator`1[MyProj.Shared.Model.WithUser`1[T]]'.
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceTable..ctor(IEnumerable`1 descriptors)
at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable`1 serviceDescriptors, Boolean validateScopes)
at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at MyProj.Program.Main(String[] args) in X:\MySolution\src\MyProj\Program.cs:line 31
这是(通用,非抽象)的验证器类:
public class WithUserCommandValidator<TCommand> : AbstractValidator<WithUser<TCommand>>
where TCommand : ICommand
{
public WithUserCommandValidator(IValidator<TCommand> commandValidator)
{
RuleFor(cmd => cmd).NotNull();
RuleFor(cmd => cmd.UserId).NotEqual(Guid.Empty);
RuleFor(cmd => cmd.Content).NotNull()
.SetValidator(commandValidator);
}
}
(不知道是很重要的,以显示WithUser<T>
类,它只是持有Guid UserId
和T Content
)。
注册偏偏喜欢这样:
someInterface = typeof(FluentValidation.IValidator<WithUser<>>);
someImplementation = typeof(Shared.Api.WithUserCommandValidator<>);
// this is for top-level command validators, injected by interface
services.AddScoped(someInterface, someImplementation);
// this is for nested validators, injected by implementation
services.AddScoped(someImplementation);
,并在运行时这些变量持有:
+ someInterface {FluentValidation.IValidator`1[MyProj.Shared.Model.WithUser`1[TCommand]]} System.Type {System.RuntimeType}
+ someImplementation {MyProj.Shared.Api.WithUserCommandValidator`1[TCommand]} System.Type {System.RuntimeType}
这似乎是正确的。
我也在SO上寻找类似的问题和疑问,但它们并没有真正相关,因为它们是关于泛型实现的,而这是一个具体实现。
我已经通过了依赖注入模块代码,并抛出异常here。由于某种原因,serviceTypeInfo.IsGenericTypeDefinition
返回false(不应该是true,因为接口类型是通用的?),因此采用else分支。在那里,相反,实现类型返回true到implementationTypeInfo.IsGenericTypeDefinition
,所以你有例外。
运行值:
+ serviceTypeInfo {FluentValidation.IValidator`1[MyProj.Shared.Model.WithUser`1[TCommand]]} System.Reflection.TypeInfo {System.RuntimeType}
+ implementationTypeInfo {MyProj.Shared.Api.WithUserCommandValidator`1[TCommand]} System.Reflection.TypeInfo {System.RuntimeType}
虽然摆弄,我试过只注册实施,也没有注册接口+实现,而且异常消失。但是如果可能的话,我想注入接口,而不是实现。
我在做什么错? TA
一些更详细信息:.NET的核心代码检查'serviceTypeInfo.IsGenericTypeDefinition',这是假的,而不是'serviceTypeInfo.IsGenericType'是真实的。但是,我不知道前者是什么意思。 – superjos