I have a fairly large application where one handler will call another handler. I have read how this is not something we should be doing:
- Calling one handler from another one, is it good?
- Dealing with Duplication in MediatR Handlers
- Can I send request using mediator in Application layer at other handler?
However, refactoring the handlers so that we don't have them calling each other would be a large undertaking.
That being said, I would like to simplify a bit how handlers use Mediator to call the other handlers.
Here is an example of what a handlers would look like:
private readonly ISender _mediator;
private readonly UserHelper _userHelper;
public Handler(ISender mediator, UserHelper userHelper) {
_mediator = mediator;
_userHelper = userHelper;
}
public async Task<CreateUserResponse> Handle(CreateUserRequest request) {
var response = await _mediator.Send(new CustomBizLogicRequest {
OrgId = request.OrganizationId,
});
// ...
Using this approach works, but I would like to change it to use a helper class that would take care of using Mediator. Something like:
public class UserHelper {
private readonly ISender _mediator;
public UserHelper(ISender mediator) {
_mediator = mediator;
}
public async Task<Result<CustomBizLogicResponse>> CustomBizLogicAsync(int orgId) =>
await _mediator.Send(new CustomBizLogicRequest {
OrgId = orgId,
});
This way we could simplify the call from the Handler
to use the injected `UserHelper:
response = await _userHelper.CustomBizLogicAsync(request.OrganizationId);
When I try to use the helper method, I get:
Cannot resolve 'MediatR.IRequestHandler`2[CustomBizLogicRequest,CustomBizLogicResponse]]' from root provider because it requires scoped service 'DbContext'.
The handler for CustomBizLogic
expects DbContext
, which I registered as:
services.AddDbContext<DbContext>(opt => {
//...
});
I did find this answer for a similar issue, but that one is a BackgroundService
, instead of a web host, so I think the lifetime for DbContext
would be different.
I'm confused why calling the hander from another handler using Mediator directly works, but moving the call to the helper class somehow changes the scope.