如何在 CQRS .NET Core 中使用 Base Handler Class 解决构造函数中的注入

How to Solve Injections In Constructor With Base Handler Class In CQRS .NET Core

我正在尝试创建一个 CQRS 模式的应用程序。我有处理程序 classes 来管理我的业务逻辑。但是处理程序构造函数有很多依赖关系,这会导致大量样板文件。是否有任何解决方案可以让我将所有这些项目注入基本处理程序 class 并使我的处理程序更纯净?

public class Handler : IRequestHandler<Command>
{
    private readonly DataContext _context;
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly string _value;
    private readonly IMapper _mapper;
    private readonly IEventBus _bus;

    public Handler(
        DataContext context,
        IHttpContextAccessor httpContextAccessor,
        IMapper mapper,
        IEventBus bus)
    {
        _context = context;
        _httpContextAccessor = httpContextAccessor;
        _mapper = mapper;
        _bus = bus;

        if (httpContextAccessor.HttpContext != null)
            _value = _httpContextAccessor.HttpContext.Items["Value"].ToString();
    }

    public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
    {
        if (true) return Unit.Value;

        throw new Exception("Error Message");
    }
}

这是一个常见问题。

Facade Pattern 或 Facade 服务很好地解决了这个问题。

您所做的是创建一个新服务,作为其余服务的包装器。这样你只注入一个服务。

单一职责原则提醒

您在 class 中注入了太多服务,这是 single responsibility principle 滥用的典型代码味道。您应该尝试将您的功能拆分为不同的 classes。这将帮助您编写更清晰的代码。