question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Calling one handler from another one, is it good?

See original GitHub issue

Hello all, I recently started using Mediatr in my web api project and I am pretty happy with that. But I have one issue, my web API accepts a request with following JSON data.

{
	"Title": "First note",   //Note title  
	"Details" : "Hello World",  // Note detail
	"UserId": 1 // User id who created this note
}

As u can see above the UserId is 1 which is nothing but the user with Id 1 in database. But while saving this note (about JSON object is Note object), the repository method accepts an actual User object rather than UserId. So before saving in db I need to get the user details who has Id 1 and then initialize the user property of note object with those details and then save it to the database. So I need to let u know that I already have a query that retrieves the specific user with its UserId passed to it. So my question is that can I call that query handler bypassing user id with it and then get that user and then save my note to the database? Is it good practice? I did research on it, some people used the pipeline (I don’t know much about it) to achieve it.

public class CreateNoteCommandHandler : IRequestHandler<CreateNoteCommand>
    {
        private readonly INoteRepository _noteRepository;
        private readonly IUserRepository _userRepository;

        public CreateNoteCommandHandler(INoteRepository noteRepository, IUserRepository userRepository)
        {
            _noteRepository = noteRepository;
            _userRepository = userRepository;

        }

        public Task<Unit> Handle(CreateNoteCommand request, CancellationToken cancellationToken)
        {

            // Call user repository to get that specific user 
            var user = _userRepository.Get(request.Note.UserId);

                                    // OR


            // should i inject mediator here and call corresponding method
            // OR var user _mediator.Send(new GetUserById(request.Note.UserId);

            var note = new Note
            {
                User = user,
                Details = request.Note.Details,
                Title = request.Note.Title
            };

            _noteRepository.Add(note);
            return Task.FromResult(Unit.Value);
        }
    }

I have already read this article BTW https://lostechies.com/jimmybogard/2016/12/12/dealing-with-duplication-in-mediatr-handlers/

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

6reactions
jbogardcommented, Sep 3, 2019

To answer your first question - we’ve done nested handlers in the past on projects, and it’s never really turned out well. The indirection of a handler is good at the application level, but just got confusing once we got inside a handler (and it introduced coupling). I’d do exactly as you show above.

A broader question though is “should I have to query the database to get a FK entity”, and these days, I prefer “no”.

In your model, I’d have two properties - UserId and User. I don’t know what your persistence strategy, but ORMs like EF can handle this just fine.

It saves a query to the database when you just want to insert something.

0reactions
nibro7778commented, Sep 15, 2021

I agreed with @jbogard and we should avoid the mediator command handler calling another mediator command handler but it should be fine to publish the mediator single/multiple events from the same command handler. Please correct me if I am the wrong @jbogard?

Read more comments on GitHub >

github_iconTop Results From Across the Web

c# - Is it OK to have one handler call another when using ...
1 Answer 1 ... Jimmy Bogard (the author of mediatr) is saying you should avoid this. ... Also note that if you are...
Read more >
Calling an Handler from another one
Hi, I'd like to instantiate and call another handler from the current handler using the same method, using it to add to (or...
Read more >
Why command should not call command in CQRS?
In conclusion, while it is technically possible for a command to call another command in CQRS, it is generally not recommended. The mediator ......
Read more >
Does CQRS Handler can invoke another Handler because ...
I have read DDD Vaughn Vernon book. There is a info about CQRS architecture. He mention that Handler can only do one Handler...
Read more >
Chaining Handlers with MediatR : r/csharp
The fact that you want one handler to call another handler suggests to me that you're going down that anti-pattern.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found