Services
Application services orchestrate use cases for external callers. Domain services encapsulate business rules that span multiple aggregates.
Guides: Application Services ยท Domain Services
BaseApplicationService
Bases: Element, OptionsMixin
Base class for application services. An application service runs one aggregate's use cases for outside callers, such as API endpoints, CLI commands and background jobs.
A use-case method loads aggregates, calls their methods and saves the
results. Business logic stays in the domain model. Callers call the method
directly and get its return value. Mark each use-case method with
@use_case to run it inside a UnitOfWork. The Application Services
guide covers usage.
Meta Options
| Option | Type | Description |
|---|---|---|
part_of |
type |
The aggregate class this service orchestrates. Required. |
Example::
@domain.application_service(part_of=Order)
class OrderService(BaseApplicationService):
@use_case
def place_order(self, order_data: dict) -> Order:
order = Order(**order_data)
repo = domain.repository_for(Order)
repo.add(order)
return order
use_case
use_case(func: Callable[..., Any]) -> Callable[..., Any]
Decorator to mark a method as a use case in an Application Service.
| PARAMETER | DESCRIPTION |
|---|---|
func
|
The method to be decorated.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable[..., Any]
|
The decorated method. |
Source code in src/protean/core/application_service.py
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | |
BaseDomainService
BaseDomainService(
*aggregates: BaseAggregate | list[BaseAggregate],
)
Bases: Element, OptionsMixin
Base class for domain services that encapsulate business logic spanning multiple aggregates.
Domain services are stateless, instantiated with the aggregate instances
they operate on, and must be associated with two or more aggregates via
the part_of option. Public methods (including __call__) are
automatically wrapped with pre/post invariant checks when the service
class has methods decorated with @invariant.pre or @invariant.post.
Meta Options
| Option | Type | Description |
|---|---|---|
part_of |
list |
List of two or more aggregate classes this service operates on. Required. |
Example::
@domain.domain_service(part_of=[Order, Inventory])
class PlaceOrderService(BaseDomainService):
@invariant.post
def order_should_have_items(self):
if not self._aggregates[0].items:
raise ValidationError({"items": ["Order must have items"]})
def __call__(self):
order, inventory = self._aggregates
inventory.reserve(order.items)
order.confirm()
Initialize a DomainService with one or more aggregates.
| PARAMETER | DESCRIPTION |
|---|---|
*aggregates
|
One or more aggregates to operate on.
TYPE:
|
Source code in src/protean/core/domain_service.py
74 75 76 77 78 79 80 | |