繁体   English   中英

CQRS 命令/查询装饰器

[英]CQRS Commands/Queries decorators

如何为IQueryHandlerICommandHandler添加自定义装饰器?

我正在尝试使用AutofacMediatR库在简单的控制台应用程序中实现 CQRS 模式。

该项目具有下一个结构:

在此处输入图片说明

我想以这种方式处理命令和查询:

  • 请求处理程序装饰器应用
  • 命令/查询处理程序装饰器应用
  • 命令/查询处理程序做一些事情
  • 命令/查询处理程序装饰器整理
  • 请求处理程序装饰器整理

主文件:

internal class Program
{
    static async Task Main(string[] args)
    {
        var container = ConfigureCQRS();
        using var scope = container.BeginLifetimeScope();

        var mediatr = scope.Resolve<IMediator>();

        await mediatr.Send(new MyCommand("Command1"));
        await mediatr.Send(new MyQuery("Query1"));
    }

    private static IContainer ConfigureCQRS()
    {
        var builder = new ContainerBuilder();

        builder.RegisterModule(new MediatRModule(typeof(Program).Assembly));
        builder.RegisterGenericDecorator(typeof(LoggingRequestHandlerDecorator<,>), typeof(IRequestHandler<,>));
        builder.RegisterGenericDecorator(typeof(UnitOfWorkCommandHandlerDecorator<,>), typeof(ICommandHandler<,>));
        builder.RegisterGenericDecorator(typeof(DiagnosticQueryHandlerDecorator<,>), typeof(IQueryHandler<,>));

        return builder.Build();
    }
}

MediatRModule.cs:

internal class MediatRModule : Autofac.Module
{
    private readonly Assembly[] assemblies;

    internal MediatRModule(params Assembly[] assemblies)
    {
        this.assemblies = assemblies;
    }

    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterMediatR(assemblies);

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

        foreach (var openHandlerType in openHandlerTypes)
        {
            builder.RegisterAssemblyTypes(this.assemblies)
             .AsClosedTypesOf(openHandlerType)
             .AsImplementedInterfaces();
        }

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

        builder.Register<ServiceFactory>(outerContext =>
        {
            var innerContext = outerContext.Resolve<IComponentContext>();

            return serviceType => innerContext.Resolve(serviceType);
        })
            .InstancePerLifetimeScope();
    }
}

带装饰器的典型命令:

internal record MyCommand(string Text) : CommandBase<string>;

internal class MyCommandHandler : ICommandHandler<MyCommand, string>
{
    public Task<string> Handle(MyCommand command, CancellationToken cancellationToken)
    {
        Console.WriteLine($"Command result: {command.Text}");
        return Task.FromResult(command.Text);
    }
}

典型的请求处理程序装饰器:

internal class LoggingRequestHandlerDecorator<TRequest, TResult> :
    IRequestHandler<TRequest, TResult>
    where TRequest : IRequest<TResult>
{
    private readonly IRequestHandler<TRequest, TResult> _decorated;

    public LoggingRequestHandlerDecorator(IRequestHandler<TRequest, TResult> decorated)
    {
        this._decorated = decorated;
    }

    public async Task<TResult> Handle(TRequest request, CancellationToken cancellationToken)
    {
        Console.WriteLine("LoggingRequestHandlerDecorator start");
        var result = await _decorated.Handle(request, cancellationToken);
        Console.WriteLine("LoggingRequestHandlerDecorator end");
        return result;
    }
}

典型的命令处理程序装饰器:

internal class UnitOfWorkCommandHandlerDecorator<TCommand, TResult> :
    ICommandHandler<TCommand, TResult>
    where TCommand : ICommand<TResult>
{
    private readonly ICommandHandler<TCommand, TResult> _decorated;

    public UnitOfWorkCommandHandlerDecorator(ICommandHandler<TCommand, TResult> decorated)
    {
        _decorated = decorated;
    }

    public async Task<TResult> Handle(TCommand command, CancellationToken cancellationToken)
    {
        Console.WriteLine("UnitOfWorkCommandHandlerDecorator start");
        var result = await _decorated.Handle(command, cancellationToken);
        Console.WriteLine("UnitOfWorkCommandHandlerDecorator end");
        return result;
    }
}

完整项目发布在 github: github.com/LeftTwixWand/CommandQueryDecorators

好的,我已经买下了这个。 只需要在装饰器的构造函数中接受 IRequestHandler 即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM