从 C# 中的 Mediatr 行为中获取命令处理程序

问题描述 投票:0回答:2

在命令处理程序上,我想设置事务处理。我不想在所有方法上设置事务,因为它有性能泄漏。本质上,我想设置这个属性来检查是否应该设置事务。 目前,我可以访问请求属性,但我想访问 handler 属性

[SqlTransactionAttribute]只是一个简单的标记属性

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

现在的问题是在pipeline behavior中如何判断一个handler是否有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);
    }
}
}

将此属性添加到命令允许我读取它(从 TRequest),但是,我更愿意从处理程序中读取它,因为逻辑必须在处理程序中并且它将更具可读性。

c# cqrs mediatr
2个回答
5
投票

将 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);
        }
    }
}

0
投票

我试过了,它有效

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)
{
    var hasTransactionAttribute = typeof(TRequest).GetCustomAttributes(typeof(SqlTransactionAttribute), false).Any();
    //how to get command handler 
    if (hasTransactionAttribute)
    {
        await HandleSqlTransaction(next);
    }
}
}
© www.soinside.com 2019 - 2024. All rights reserved.