如何从类类型

时间:2017-09-22 20:39:42

标签: c# autofac

配置Autofac模块时遇到小问题。我想用命令模式解决IValidator(流利验证器)服务,但我不知道如何。

以下是我的命令:

public interface ICommand

public interface ICreateCommand<TDto> : where TDto is IDto

public CreateUserCommand : ICreateCommand<UserDto>

这是我的验证员:

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

我希望在解析CreateCommandValidator时获得IValidator<CreateUserCommand>,但我只获得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();

1 个答案:

答案 0 :(得分:0)

AbstractValidator是否继承了IValidator?

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

var types = assembly.GetTypes().Where( t => t.IsClosedTypeOf( typeof( IValidator<> ) ) );
我有小提琴。也许你可以在那里找到解决方案https://dotnetfiddle.net/fw4IBw