简体   繁体   中英

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

I am trying to create a CQRS-patterned application. I have handler classes to manage my business logic. But the handler constructors have many dependency and this leads to a lot of boilerplate. Is there any solution that allows me to inject all these items in a base handler class and make my handler more pure?

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

It is a common problem.

It is addressed very well with the Facade Pattern or Facade services.

What you do is you create a new service that works as a wrapper for the rest. In this way you inject only one service.

Single responsibility principle alert

You inject too many services in your class and this is typical code smell for single responsibility principle abuse. You should try to split your functionality in different classes. That would help you write cleaner code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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