仅针对特定接口类型(命令)执行MediatR预处理器

时间:2017-12-31 22:14:42

标签: c# generics autofac cqrs mediatr

[注意:这是"替代品"题。第一个是基于我的主要项目的代码,所以我用一个单一用途的项目代码重做了这个问题,更清楚地说明了原理。问题仍然存在,只是更好地呈现。]

情景

我尝试使用MediatR管道行为和Autofac在CQRS请求管道上设置命令预处理器以进行请求路由。我的目标是预处理器仅针对命令(ICommand<>)而不是所有请求(IRequest<>)运行,这将导致预处理器执行命令,查询和事件。

问题

我可以让我的GenericPreProcessor或任何其他预处理器适用于所有类型的请求,但我曾经尝试过任何方法来过滤"注入要么返回错误,要么根本不执行所需的预处理器。

我在Autofac中的所有请求管道配置如下所示:

// Pipeline pre/post processors
builder
    .RegisterGeneric(typeof(RequestPostProcessorBehavior<,>))
    .As(typeof(IPipelineBehavior<,>));

builder
    .RegisterGeneric(typeof(RequestPreProcessorBehavior<,>))
    .As(typeof(IPipelineBehavior<,>));

// Works as desired: Fires generic pre-processor for ALL requests, both cmd and query
builder
    .RegisterGeneric(typeof(GenericRequestPreProcessor<>))
    .As(typeof(IRequestPreProcessor<>));

// Works for all requests, but I need a way to limit it to commands
builder
    .RegisterGeneric(typeof(MyCommandPreProcessor<>))
    .As(typeof(IRequestPreProcessor<>));

从概念上讲,我试图做其中任何一项失败的事情:

builder
    .RegisterGeneric(typeof(MyCommandPreProcessor<>)) // Note generic
    .As(typeof(IRequestPreProcessor<ICommand<>>));
    // Intellisense error "Unexpected use of an unbound generic"

builder
    .RegisterType(typeof(MyCommandPreProcessor)) // Note non-generic
    .As(typeof(IRequestPreProcessor<ICommand<>>)); 
    // Intellisense error "Unexpected use of an unbound generic"

builder
    .RegisterType(typeof(MyCommandPreProcessor)) // Note non-generic
    .As(typeof(IRequestPreProcessor<ICommand<CommonResult>>)); 
    // No errors, but MyCommandPreProcessor not firing

我正在为MyCommandPreProcessor尝试几种不同的配置,一种是通用的,一种是非泛型的,但我很难接受:

public class MyCommandPreProcessor<TRequest> : IRequestPreProcessor<TRequest>
{
    public Task Process(TRequest request, CancellationToken cancellationToken)
    {
        Debug.WriteLine("***** MYCOMMAND PREPROCESSOR CALLED *****");
        return Task.CompletedTask;
    }
}

- OR -

public class MyCommandPreProcessor : IRequestPreProcessor<IRequest<ICommonResponse>>
{
    public Task Process(TRequest request, CancellationToken cancellationToken)
    {
        Debug.WriteLine("***** MYCOMMAND PREPROCESSOR CALLED *****");
        return Task.CompletedTask;
    }
}

我的问题

关于我如何注册预处理器的任何想法,该预处理器仅限于激发IRequest&lt;&gt;封闭类型的ICommand&lt;&gt;?

的类型

支持材料

GitHub上的项目

可以在https://github.com/jhoiby/MediatRPreProcessorTest

查看或克隆整个最小样本项目

Autofac MediatR配置

一个工作配置,所有请求都有一个GenericRequestPreProcessor。

        builder.RegisterAssemblyTypes(typeof(IMediator).GetTypeInfo().Assembly).AsImplementedInterfaces();

        var mediatrOpenTypes = new[]
        {
            typeof(IRequestHandler<,>),
            typeof(IRequestHandler<>),
            typeof(INotificationHandler<>)
        };

        foreach (var mediatrOpenType in mediatrOpenTypes)
        {
            // Register all command handler in the same assembly as WriteLogMessageCommandHandler
            builder
                .RegisterAssemblyTypes(typeof(MyCommandHandler).GetTypeInfo().Assembly)
                .AsClosedTypesOf(mediatrOpenType)
                .AsImplementedInterfaces();

            // Register all QueryHandlers in the same assembly as GetExternalLoginQueryHandler
            builder
                .RegisterAssemblyTypes(typeof(MyQueryHandler).GetTypeInfo().Assembly)
                .AsClosedTypesOf(mediatrOpenType)
                .AsImplementedInterfaces();
        }

        // Pipeline pre/post processors
        builder.RegisterGeneric(typeof(RequestPostProcessorBehavior<,>)).As(typeof(IPipelineBehavior<,>));
        builder.RegisterGeneric(typeof(RequestPreProcessorBehavior<,>)).As(typeof(IPipelineBehavior<,>));
        builder.RegisterGeneric(typeof(GenericRequestPreProcessor<>)).As(typeof(IRequestPreProcessor<>));
        // builder.RegisterGeneric(typeof(GenericRequestPostProcessor<,>)).As(typeof(IRequestPostProcessor<,>));
        // builder.RegisterGeneric(typeof(GenericPipelineBehavior<,>)).As(typeof(IPipelineBehavior<,>));

        builder.Register<SingleInstanceFactory>(ctx =>
        {
            var c = ctx.Resolve<IComponentContext>();
            return t => c.Resolve(t);
        });

        builder.Register<MultiInstanceFactory>(ctx =>
        {
            var c = ctx.Resolve<IComponentContext>();
            return t => (IEnumerable<object>)c.Resolve(typeof(IEnumerable<>).MakeGenericType(t));
        });

MyCommandPreProcessor类

我正在尝试这两种,通用和非通用:

public class MyCommandPreProcessor<TRequest> : IRequestPreProcessor<TRequest>
{
    public Task Process(TRequest request, CancellationToken cancellationToken)
    {
        Debug.WriteLine("***** MYCOMMAND PREPROCESSOR CALLED *****");
        return Task.CompletedTask;
    }
}

- AND -

public class MyCommandPreProcessor : IRequestPreProcessor<IRequest<ICommonResponse>>
{
    public Task Process(TRequest request, CancellationToken cancellationToken)
    {
        Debug.WriteLine("***** MYCOMMAND PREPROCESSOR CALLED *****");
        return Task.CompletedTask;
    }
}

继承结构

// Requests

IMediatR.IRequest<TResponse>
    <- IMessage<TResponse>
        <- ICommand<TResponse>
            <- concrete MyCommand : ICommand<CommonResponse>
        <- IQuery<TResponse>
            <- concrete MyQuery : IQuery<CommonResponse>

// Request Handlers

IMediatR.IRequestHandler<in TRequest,TResponse>
    <- IMessageHandler<in TRequest,TResponse>
        <- ICommandHandler<in TRequest,TResponse> 
            <- concrete MyCommandHandler : ICommandHandler<MyCommand,CommonResponse>
        <- IQueryHandler<In TRequest,TResponse>
            <- concrete MyQueryHandler : IQueryHandler<MyQuery,CommonResponse>

// CommonResponse - A POCO that returns result info

ICommonResponse
    <- concrete CommonResponse

命令

public interface IMessage<TResponse> : MediatR.IRequest<TResponse>
{
}

public interface ICommand<TResponse> : IMessage<TResponse>
{
}

public class MyCommand : ICommand<CommonResponse>
{
}

命令处理程序

public interface IMessageHandler<in TRequest, TResponse> 
    : MediatR.IRequestHandler<TRequest, TResponse> 
        where TRequest : IRequest<TResponse>
{
}

public interface ICommandHandler<in TRequest, TResponse> 
    : IMessageHandler<TRequest, TResponse> 
        where TRequest : IRequest<TResponse>
{
}

public class MyCommandHandler : ICommandHandler<MyCommand, CommonResponse>
{
    public async Task<CommonResponse> Handle(
        MyCommand request, 
        CancellationToken cancellationToken)
    {
        Debug.WriteLine("   ***** Command handler executing *****");

        return
            new CommonResponse(
                succeeded: true,
                data: "Command execution completed successfully.");
    }
}

预处理器注入目标(在MediatR管道代码中)

接收注入的IRequestPreProcessor的构造函数&lt;&gt;是:

public RequestPreProcessorBehavior(IEnumerable<IRequestPreProcessor<TRequest>> preProcessors)
    {
        ...
    }

可以在文件第17行的Github上看到:

https://github.com/jbogard/MediatR/blob/master/src/MediatR/Pipeline/RequestPreProcessorBehavior.cs

谢谢!

1 个答案:

答案 0 :(得分:0)

我和您的情况完全相同,我认为问题出在RequestPreProcessorBehavior<TRequest, TResponse>并没有将所有类型都传递给IRequestPreProcessor<TRequest>

您要么:

  1. 没有任何限制:在每个 request中的MyCommandPreProcessor<TRequest>中检查IRequestPreProcessor的类型:
public Task Process(TRequest request, CancellationToken cancellationToken)
{
    var isCommand = typeof(TRequest).GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICommand<>));
    if (isCommand)
    {
        // Magic
    }
}
  1. 创建自己的预处理行为,以揭示TRequest中的IPipelineBehavior<TRequest, TResponse>
public interface IRequestPreProcessor<in TRequest, TResponse> : IRequestPreProcessor<TRequest>
    where TRequest : IRequest<TResponse>
{
}


public class MyRequestPreProcessorBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : IRequest<TResponse>
{
    private readonly IEnumerable<IRequestPreProcessor<TRequest, TResponse>> _preProcessors;

    public RequestPreProcessorBehavior(IEnumerable<IRequestPreProcessor<TRequest, TResponse>> preProcessors)
    {
        _preProcessors = preProcessors;
    }

    public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
        foreach (var processor in _preProcessors)
        {
            await processor.Process(request, cancellationToken).ConfigureAwait(false);
        }

        return await next().ConfigureAwait(false);
    }
}

使用选项2,您可以将约束添加到为命令/查询特定的预处理器实现IRequestPreProcessor<TRequest, TResponse>的任何类中。