DDD / CQRS - Does a request handler (or controller) can throw exceptions defined at the domain level? - domain-driven-design

Good morning,
Let's say, we've a domain defining an exception such as ObjectNotFoundException which expect an identifier (VO), defined at the domain model.
Question
Can we throw domain exceptions from the request handlers directly, for instance:
class ObjectRequestHandler implements RequestHandler
{
...
public function __invoke(Request $request, Response $response)
{
// Will self-validate and throw an exception if not a valid UUID
$objectId = ObjectId::fromString(strval($request->param('object_id'])));
$object = $this->repository->find((string)$objectId);
if (NULL === $object) {
// Exception defined at the domain level...
throw new ObjectNotFoundException($objectId);
}
...
}
}
Doing this also lead to usage of the identifier VO in the request handler... It MUST be also noted that the throwed exception will be catched by the default exception handler which in turn, will prepare and send a JSON response.
Finally, note that the request handler here, is an implementation detail, not part of the question. Please don't comment about it.
Thank you.

Your example shows the correct usage of the repository to fetch an object from the data store based on an identifier.
Let's unpack and expand the workflow a little more to fit the paradigms of DDD, to help answer the question:
API Controller (or Request Handler) would invoke an Application Service with request params sent by the callee.
Request params forwarded to the Application Service can be simple data (like JSON) or can be objects (like DTOs)
Application Service has access to the correct repository associated with the object.
Repositories are outside the domain layer
Application Service would load the objects into memory using these repositories before handing over the control to (or invoking a method in) the domain layer.
The ObjectNotFound error is thrown typically from the repository if no object is found for the given identifier
The domain layer typically receives all objects it needs to work on from the Application Service or builds objects using factory methods.
The actual process is all about assigning or transforming attribute values according to business rules while ensuring invariant rules are satisfied. So the kind of errors that Domain Layer throws is Business Rule Errors (or Validation Errors).
So,
ObjectNotFoundException is not a Domain Exception
You are not at the domain level yet, so calling the identifier as a ValueObject is incorrect
Ignoring Application Services for a moment, you are spot on in your usage of the concept. The code example is correct in structure. It's just the terms that need to be clarified.

Related

Doubts on application structure and communication directions

I'm currently building a CQS-style DDD-application. I'm having some doubts on how all 'components' work with each other.
But first I'll give a brief overview about the application's structure:
ApplicationService
-> Receives command objects
-> doesn't return any results
-> Acts on Domain model
-> Speaks with Aggregate repository for domain modifications
QueryService
-> Bypasses domain model; doesn't speak with Aggregate Repositories
-> Executes queries against database to populate view
-> Returns 'Representation' objects
REST Controller
-> Receives HTTP requests and binds 'body content' & request params to Command objects
-> delegates to ApplicationService for POST, PUT & DELETE requests
-> Always returns at least some HTTP code
-> delegates to QueryService for GET requests
Infrastructure
-> Handles persistence to DB
-> Contains some scheduling operations
-> Handles foreign domain events our domain model is 'interested' in
'Open Host'
-> This is mainly a Facade to be used by other domains
-> Facade delegates methods to ApplicationService for domain modifications and to QueryService for data retrieval (bypassing Repositories)
My Questions:
Is it OK that a DomainEventHandler corresponds with a Repository and invokes some methods on a Aggregate? Or should it always correspond with an ApplicationService?
QueryService returns 'Representation' objects. These are used by UI AND by 'Open Host' Facade as return value. Is it OK these objects are reused as return value by Facade? Or should Facade create their own Objects, even the results are basically the same?
ApplicationService takes 'Commands' as input parameters. Is it OK these Commands are also used by the Open Host Facade? Or should the Facade only accept primitive values and convert them to Commands when delegating to ApplicationService?
DomainEventHandlers seem to reside on 'Infrastructure' layer. Is it possible that an ApplicationService or Domain Service also subscribes to an Domain Event? Or is this always an Infrastructure responsibility?
All advice is very welcome!
Is it OK that a DomainEventHandler corresponds with a Repository and invokes some methods on a Aggregate? Or should it always correspond with an ApplicationService?
In my experience, any handlers are application services.
QueryService returns 'Representation' objects. These are used by UI AND by 'Open Host' Facade as return value. Is it OK these objects are reused as return value by Facade? Or should Facade create their own Objects, even the results are basically the same?
There is a lot of discussion here about the differences between Open Host service and Application Service. It is not clear to me who would be using Open Host service, or why it exists.
ApplicationService takes 'Commands' as input parameters. Is it OK these Commands are also used by the Open Host Facade? Or should the Facade only accept primitive values and convert them to Commands when delegating to ApplicationService?
I would pass in primitives on the edges of the application and convert them into commands which are then handled in the Application Services
DomainEventHandlers seem to reside on 'Infrastructure' layer. Is it possible that an ApplicationService or Domain Service also subscribes to an Domain Event? Or is this always an Infrastructure responsibility?
I've always considered my handlers to be Application Services - things that are responsible for orchestrating a user case. So the use case might be "when EventX is received, send an email and update the database". In this example, you would probably consider "the code that sends the email" and "the code that saves to the database" to be infrastructure concerns, but the handler itself would not be.
public class ExampleHandler : IHandle<ExampleEvent>
{
private IRepository _repo;
private ISendEmails _emailer;
public ExampleHandler(Repository repo, ISendEmails emailer)
{
.... set the private fields..
}
public void When(ExampleEvent event)
{
_emailer.Send(event.whatever);
_repo.Save(something);
}
}
To be honest, I don't really think in terms of layers - i prefer a hexagonal architecture style of thinking. In the above example, the event handlers would just have dependencies injected into them and then go about their business.

autofac and multithreading

when doing parallel/multithreading, if there are dependencies that are not thread safe, what kind of instance method can be used with autofac to get an instance per thread? from what I know, autofac is the kind of DI container for certain framework like asp.net/mvc but for the rest of the app type like windows service, it does not have any support. in my scenario, i am doing multithreading for a windows service that also hosting a web api service. what kind of registration can be used so that it will work for web api instanceperhttprequest and instanceperlifetimescope. two separate container?
EDIt:
using this parallel extension method here:
public static Task ForEachAsync<T>(this IEnumerable<T> source, int dop, Func<T, Task> body)
{
return Task.WhenAll(
from partition in Partitioner.Create(source).GetPartitions(dop)
select Task.Run(async delegate
{
using (partition)
{
while (partition.MoveNext())
{
await body(partition.Current);
}
}
}));
}
so the body will be use to do the work. DI will need to be inside of the body func.
It doesn't matter what kind of application you run; the pattern is always the same. You should resolve one object graph per request. In a web application, a request means a web request, in a windows service, a request is usually a timer pulse.
So in a windows service, each 'pulse' you start a new lifetime scope, and within this scope you resolve your root object and call it.
If however, you process items in parallel within a single request, you should see each processed item as a request of its own. So that means that on each thread you should start a new lifetime scope and resolve a sub object graph from that scope and execute that. Prevent passing services that are resolved from your container, from thread to thread. This scatters the knowledge of what is thread-safe, and what isn't throughout the application, instead of keeping that knowledge centralized in the startup path of your application where you compose your object graphs (the composition root).
Take a look at this article about working with dependency injection in multi-threaded applications. It's written for a different DI library, but you'll find most of the advice generically applicable to all DI libraries.

What is lost from the stack when a service handles async messages in ServiceStack?

I'm using the messaging feature of ServiceStack for back end transactions I expect to involve database locks where consistency is very important.
I've registered handlers as explained in the documentation:
mqHost.RegisterHandler<Hello>(m => {
return this.ServiceController.ExecuteMessage(m);
});
I've noticed the Filters don't get called. Presumably, they're really "Http" filters similar to MVC. So it makes sense they're ignored.
How does Authorization work with message handlers, is it ignored too?
And as I want to keep my async services internal, and always async, is there any benefit in making them inherit from ServiceBase at all?
As I'm thinking of creating another envelop layer between IMessage and Body for some Identity data that can be passed from my public services out of AuthSession and to the Async service.

How does domain objects and services interact in DDD?

'So it was in this context we created a Order.adjust() method that delegated the call to OrderAdjust Service.
Having Order.adjust() has an advantage that it makes Order own the adjust operation.'
How is this done? Is the domain service injected?
$order = new Order();
$order->adjust(???);
How can the domain service do operations on domain entities when it's stateless?
If a domain service is injected into an entity, methods can only be called on the reference and thus state must exist?
$service = DomainService();
$entity = DomainEntity();
$entity->operation($service);
// Inside DomainEntity
public function operation(DomainService &$service)
{
// Operations are delegated to the domain service reference
$service->operation();
$service->operation2();
}
$another_entity = AnotherDomainEntity();
// What happened in the first object must be known here
// otherwise what's the point?
$another_entity->operation($service);
Shouldn't it be done like this or in an application service?
$domain_service = new DomainService();
$entity = new DomainEntity();
$another_entity = new AnotherDomainEntity();
$domain_service->performOperation($entity, $another_entity);
How are the operations between domain entities/objects done?
How do domain objects in general communicate? Where are they instantiated?
Code examples would be greatly appreciated.
Source:
http://stochastyk.blogspot.no/2008/05/domain-services-in-domain-driven-design.html
The question is similar to this one: https://softwareengineering.stackexchange.com/a/62193/19252.
The blog post you referenced does a good job on your question. To make it short: If it can be done (and unit-tested!) in a model, do it there. Domain services are rather exception than a rule.
Let me quote that post:
"- Are'nt Services bad and should'nt we use all objects as per OO?
Yes, Services tend to stand orthogonal to Object Oriented Design. [...] There is a huge tendency in the modelling world to use excessive number of services"
As for me, the tendency comes from flaws of .NET/Java persistence architectures, like impossibility to put business logic into setter methods.

Interface with service layer or domain objects themselves? (DDD)

I'm still learning about DDD and I have these two (probably simple) questions:
If a Factory creates new object/graph/aggregate instances, but also "reconstitutes" objects/graphs from the Repository, then:
(1) Does your service layer functions/jobs/tasks/unit-of-work call into the Factory or a behavioural method on the Entity instance or a DomainService function? I'm lost as to the call stack based on the responsibility of these components.
(2) Do Entity instances even have "behavioural methods" like above? For example does a Post have p.UpdatePost(string bodyText) or is that not a concern of the domain model and so the same should be achieved with the Repository? Or the service layer function, should it be calling the Repository in this case and the entity instance simply have behavioural methods that are specific to the domain and not persistence? But then, why does it sound like "updating a post" is a domain function when that's the user's goal?
You can see I'm all over the place. Please help.
(1) Does your service layer functions/jobs/tasks/unit-of-work call into the Factory or a behavioral method on the Entity instance or a DomainService function? I'm lost as to the call stack based on the responsibility of these components.
Usually - top level retrieves necessary aggregate root and calls a function on it. Sometimes top level retrieves multiple aggregate roots and pass them to domain service, but not often because domain service is a quite strong sign that there is unrecognized aggregate root. At the end - top level ensures aggregate root is persisted.
(2) Do Entity instances even have "behavioural methods" like above? For example does a Post have p.UpdatePost(string bodyText) or is that not a concern of the domain model and so the same should be achieved with the Repository? Or the service layer function, should it be calling the Repository in this case and the entity instance simply have behavioural methods that are specific to the domain and not persistence? But then, why does it sound like "updating a post" is a domain function when that's the user's goal?
Yes, they do. Domain model should be aware of it's state changes. And that's much more beneficial as it seems at first. Great thing about this is that You gain extensibility point. If client will walk week later to You and say that he wants system to check additional things when user updates post - instead of searching every line of post.bodyText="new value", You will be able to go straight to post.UpdatePost method and attach necessary things there.
On the other hand - CRUD is not mutually exclusive with domain driven design. E.g. - in my application, management of users and their roles is uninteresting enough that I'm not even trying to model it granularly. You need to recognize parts what matters in business Your application is describing and working with.
Keep in mind that domain driven design makes sense for complex applications only. Simple blog application doesn't need it.
(3) Am I wrong in assuming that a service layer (not Domain Services) should encapsulate how an interface interacts with the Domain Layer?
As I see it - application services are more for orchestrating infrastructure. If there is no infrastructure involved - then application service loses value:
Application services basically are just facades. And every facade is bad if complexity it adds overweights problems it solves.
Inside domain:
//aggregate root is persistence ignorant.
//it shouldn't reference repository directly
public class Customer{
public string Name {get; private set;}
public static Customer Register(string name){
return new Customer(name);
}
protected Customer(string name){
//here it's aware of state changes.
//aggregate root changes it's own state
//instead of having state changed from outside
//through public properties
this.Name=name;
}
}
//domain model contains abstraction of persistence
public interface ICustomerRepository{
void Save(Customer customer);
}
Outside of domain:
public class CustomerRepository:ICustomerRepository{
//here we actually save state of customer into database/cloud/xml/whatever
public void Save(Customer customer){
//note that we do not change state of customer, we just persist it here
_voodoo.StoreItSomehow(customer);
}
}
//asp.net mvc controller
public class CustomerController{
public CustomerController(ICustomerRepository repository){
if (repository==null)throw new ArgumentNullException();
_repository=repository;
}
public ActionResult Register(string name){
var customer=Customer.Register(name);
_repository.Save(customer);
}
}

Resources