小编She*_*ari的帖子

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

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

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

[SqlTransactionAttribute]
public class LoginUserCommandHandler : IRequestHandler<LoginUserCommand, TokenDTO>
{
 //Command handler implementation
}
Run Code Online (Sandbox Code Playgroud)

现在的问题是,在管道行为中如何确定一个处理程序是否具有 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);
    }
}
}
Run Code Online (Sandbox Code Playgroud)

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

c# cqrs mediatr

1
推荐指数
1
解决办法
1999
查看次数

标签 统计

c# ×1

cqrs ×1

mediatr ×1