2017-09-22 72 views
1

配置Autofac模块时出现小问题。我想用命令模式解决一个IValidator(Fluent Validator)服务,但我不知道如何。如何从类类型中解析通用接口

这里是我的命令:

public interface ICommand 

public interface ICreateCommand<TDto> : where TDto is IDto 

public CreateUserCommand : ICreateCommand<UserDto> 

这里是我的验证:

public CreateCommandValidator<TDto> : AbstractValidator<ICreateCommand<TDto>> 

我想解决IValidator<CreateUserCommand>时候才能CreateCommandValidator但我只得到一个ComponentNotRegisteredException

我autofac配置:

 var assembly = typeof(CommandModule) 
      .GetTypeInfo() 
      .Assembly; 

     builder.RegisterAssemblyTypes(assembly) 
      .AsClosedTypesOf(typeof(ICommandHandler<>)) 
      .InstancePerLifetimeScope(); 

     builder.RegisterType<CommandDispatcher>() 
      .As<ICommandDispatcher>() 
      .InstancePerLifetimeScope(); 

     libraryAssembly = typeof(ICommand) 
      .GetTypeInfo() 
      .Assembly; 

     builder.RegisterAssemblyTypes(libraryAssembly) 
      .Where(x => x.IsAssignableTo<ICommand>()) 
      .AsImplementedInterfaces(); 

    builder.RegisterAssemblyTypes(libraryAssembly) 
     .AsClosedTypesOf(typeof(IValidator<>)) 
     .InstancePerLifetimeScope(); 

回答

0

不AbstractValidator继承IValidator?

基本上我注册类型是这样的:

var types = assembly.GetTypes().Where(t => t.IsClosedTypeOf(typeof(IValidator<>))); 

我有小提琴。也许你可以找到解决方案https://dotnetfiddle.net/fw4IBw