Search code examples
c#asp.netasp.net-coreautofacmediatr

Register IPipelineBehavior in ASP.NET Core 3 with autofac


I want to register pipeline behavior in my project and register that by autofac.

I implement that by this way :

public class CheckUserNameExistValidation<TRequest, TResponse> : IPipelineBehavior<CreateUserCommand, OperationResult<string>>
{
    private readonly IDomainUnitOfWork unitOfWork;

    public CheckUserNameExistValidation(IDomainUnitOfWork unitOfWork)
    {
        this.unitOfWork = unitOfWork;
    }

    public async Task<OperationResult<string>> Handle(CreateUserCommand request, CancellationToken cancellationToken, RequestHandlerDelegate<OperationResult<string>> next)
    {
        var findUserName = await unitOfWork.UsersRepository.GetUserByUsernameAsync(request.Username, cancellationToken);

        if (findUserName.Result != null)
        {
            return OperationResult<string>.BuildFailure("UserName Exist");
        }

        return await next();
    }
}

and I register this pipeline in this autofac by this way :

 container.RegisterGeneric(typeof(CheckUserNameExistValidation<CreateUserCommand, OperationResult<string>>)).
                                                        As(typeof(IPipelineBehavior<CreateUserCommand, OperationResult<string>>));

but when I run the project it show me this error:

System.ArgumentException: The type BehaviorHandler.PipeLineBehaviors.RegisterUserBehavior.CheckUserNameExistValidation2[Command.UserCommands.CreateUserCommand,Common.Operation.OperationResult1[System.String]] is not an open generic type definition. at Autofac.Features.OpenGenerics.OpenGenericRegistrationExtensions.RegisterGeneric(ContainerBuilder builder, Type implementor) at Autofac.RegistrationExtensions.RegisterGeneric(ContainerBuilder builder, Type implementer) at Framework.Configuration.AutofacConfiguration.AutoInjectServices(ContainerBuilder container)

What's the problem? How can I solve this problem?


Solution

  • RegisterGeneric is used for open generic registrations, where you register a generic type without specifying the generic type arguments.

    But that’s not what you are doing here. You are registering IPipelineBehavior<CreateUserCommand, OperationResult<string>> which is a very concrete type. It is generic but it has type arguments specified so it is like any other non-generic type.

    This means that you will have to use the regular RegisterType method:

    container.RegisterType(typeof(CheckUserNameExistValidation<CreateUserCommand, OperationResult<string>>))
        .As(typeof(IPipelineBehavior<CreateUserCommand, OperationResult<string>>));
    

    And of course, you can also use the generic version of Register then:

    container.RegisterType<CheckUserNameExistValidation<CreateUserCommand, OperationResult<string>>>()
        .As<IPipelineBehavior<CreateUserCommand, OperationResult<string>>>();