简体   繁体   English

获取 C# 中 mediatr 管道的命令处理程序

[英]Get command handler for the mediatr pipeline in C#

On command handlers, I want to set transaction handling.在命令处理程序上,我想设置事务处理。 I don't want to set transactions on all methods because it has performance leaks.我不想在所有方法上设置事务,因为它存在性能泄漏。 In essence, I want to set this attribute to check if the transaction should be set or not.本质上,我想设置这个属性来检查是否应该设置事务。 Currently, I am able to access the request attribute, but I want access to the handler attribute .目前,我可以访问 request 属性,但我想访问handler 属性

The [SqlTransactionAttribute] is just a simple marker attribute [SqlTransactionAttribute]只是一个简单的标记属性

[SqlTransactionAttribute]
public class LoginUserCommandHandler : IRequestHandler<LoginUserCommand, TokenDTO>
{
 //Command handler implementation
}

The problem now is that in the pipeline behavior how to determine whether a handler has SqlTransactionAttribute or not现在的问题是在管道行为中如何确定处理程序是否具有 SqlTransactionAttribute

public class TransactionBehavior<TRequest, TResponse> :
IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
where TResponse : notnull
{
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
    //how to get command handler 
    if (Attribute.GetCustomAttribute(typeof(handler), typeof(SqlTransactionAttribute)) != null)
    {
        await HandleSqlTransaction(next);
    }
}
}

Adding this attribute to the command allows me to read it(from TRequest), however, I'd prefer to read it from the handler as the logic must be in the handler and it will be more readable.将此属性添加到命令允许我读取它(从 TRequest),但是,我更喜欢从处理程序中读取它,因为逻辑必须在处理程序中并且它更具可读性。

Inject the RequestHandler into the constructor.将 RequestHandler 注入构造函数。

public class TransactionBehavior<TRequest, TResponse> :
    IPipelineBehavior<TRequest, TResponse>
    where TRequest : IRequest<TResponse>
    where TResponse : notnull
{
    private readonly IRequestHandler<TRequest, TResponse> requestHandler;

    public TransactionBehavior(IRequestHandler<TRequest, TResponse> requestHandler)
    {
        this.requestHandler = requestHandler;
    }

    public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
        var hasSqlTransactionAttribute = requestHandler.GetType().GetCustomAttributes<SqlTransactionAttribute>().Any();

        if (hasSqlTransactionAttribute)
        {
            await HandleSqlTransaction(next);
        }
    }
}

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

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