jbogard / MediatR

Simple, unambitious mediator implementation in .NET
Apache License 2.0
11.21k stars 1.18k forks source link

What is the best way of appling part of same logic in different handler? #97

Closed vip30 closed 7 years ago

vip30 commented 8 years ago
public class InvoiceCreateCommandHandlerAsync: AsyncRequestHandler<InvoiceCreateCommand>
{
    private readonly DbContext _db;
    public InvoiceCreateCommandHandlerAsync(
       DbContext  db)
    {
        _db= db;
    }
    protected override async Task HandleCore(InvoiceCreateCommand command)
    {
        //Transaction
        //Save Invoice DB action
        //As the invoice is added, and the stock will be stocked out
       //Stock out Logic here
           .......
       //End
       //Commit
    }
}

public class StockOutCommandHandlerAsync: AsyncRequestHandler<StockOutCommand>
{
    private readonly DbContext _db;
    public StockOutCommandHandlerAsync(
       DbContext  db)
    {
        _db= db;
    }
    protected override async Task HandleCore(StockOutCommand command)
    {
       //Stock out Logic here
           .......
       //End
    }
}

Sorry about the poor format. I would like to ask what is the best approach for applying same logic in different handler? As the stock out logic is need to provide in create invoice and also in the stock out page Thanks

abatishchev commented 8 years ago

You can inject a helper into both handlers and call shared logic method from there

vip30 commented 8 years ago

I see we can inject a service/helper for helping the stock out function, but it will not be treated as a command (But it will insert in the DB) , I just want to know is that violate the CQRS pattern with mediatR? Many Thanks

abatishchev commented 8 years ago

I don't think a handler to have a dependency is illegal, and injecting it into its ctor violates any principle. Rather follows these principles. Also it's better than inheriting both handlers from a base class (see the composition over inheritance principle)

valdisiljuconoks commented 8 years ago

Hi, I would think of StockOut logic as code fragment that does not need to treated as command separately, but it's always called from the "hosting" command -> one or another handler. StockOut code fragment makes no sense by itself, but is always executed within the command. And handler having a dependency - don't think it's illegal. Think about it as ordinary service injection for the handler.

jbogard commented 7 years ago

https://lostechies.com/jimmybogard/2016/12/12/dealing-with-duplication-in-mediatr-handlers/