Sebastian Staniak
Sebastian Staniak

Reputation: 31

How deal with query handlers as dependency?

Iam building bounded context using CQRS pattern. I prepared some queries and handlers for each. And now, in presentation layer(http REST controller) I have to use it. Question is, should I inject each handler to this controller (there is 4 queries and handlers) or use command bus and configure right handlers to specified query?

Upvotes: 1

Views: 745

Answers (2)

VoiceOfUnreason
VoiceOfUnreason

Reputation: 57377

Well, either way seems like it makes sense; that's probably a hint that you should be passing in an interface that expresses the contract that the Controller needs satisfied, and punt the implementation details down a level.

My guess is that you ultimately won't want the controller directly wired into the query handlers, because that will restrict your options in a number of use cases (example: congestion control and back pressure). But you won't know until much further down the road, so keep things loose.

Upvotes: 2

Matt Kocaj
Matt Kocaj

Reputation: 11535

In the past we've injected some sort of Query Executor into the controller and passed queries into that. eg,

public SomeController(IQueryExecutor queryExecutor) { ...

and then

var results = queryExecutor.Query(new GetSomeThings(args..));

The handler for GetSomeThings is wired up by the supporting infrastructure so you don't need to inject those. Does that make sense?


A word of warning about CQRS/CQS:

If you find you writing queries and handlers that are used at most only once or twice, or commands that are dedicated to the controller that uses them, then perhaps CQRS/CQS is an abstraction you don't actually need to be paying the extra complexity cost for.

My teams and I have found this to be true on a number of projects. Often CQRS/CQS is just another unnecessary abstraction like a Repository which dispatches to an ORM lib or a 'Service' which has one or two line dispatches to a Repository, which...
Hopefully you get the point.

I like the Rule Of Three - don't try to get reusability until you have more than 3 usages. And even then, don't jump deep into something heavy and very prescribed like CQRS/CQS if you don't need it. DDD is very kool but you can pick and choose which elements of it make sense for you. Often much of it won't make sense when you apply pragmatic reasoning.

Just my 2 c.

Upvotes: -1

Related Questions