212
CHAPTER 6 | Tackle Business Complexity in a Microservice with DDD and CQRS Patterns
{
if
(!_requestedHashCode.
HasValue
)
_requestedHashCode =
this
.
Id
.
GetHashCode
() ^
31
;
// XOR for random distribution. See:
// https://learn.microsoft.com/archive/blogs/ericlippert/guidelines-and-rules-
for-gethashcode
return
_requestedHashCode.
Value
;
}
else
return
base
.
GetHashCode
();
}
public
static
bool
operator
==(Entity left, Entity right)
{
if
(Object.
Equals
(left,
null
))
return
(Object.
Equals
(right,
null
));
else
return
left.
Equals
(right);
}
public
static
bool
operator
!=(Entity left, Entity right)
{
return
!(left == right);
}
}
The previous code using a domain event list per entity will be explained in the next
sections when
focusing on domain events.
Repository contracts (interfaces) in the domain model layer
Repository contracts are simply .NET interfaces that express the contract
requirements of the
repositories to be used for each aggregate.
The repositories themselves, with EF Core code or any other infrastructure dependencies and code
(Linq, SQL, etc.), must not be implemented within the domain model; the repositories should only
implement the interfaces you define in the domain model.
A pattern related to this practice (placing the repository interfaces in the domain model layer) is the
Separated Interface pattern. As
explained
by Martin Fowler, “Use Separated Interface to define an
interface in one package but implement it in another. This way a client that needs the dependency to
the interface can be completely unaware of the implementation.”
Following the Separated Interface pattern enables the application layer (in
this case, the Web API
project for the microservice) to have a dependency on the requirements defined in the domain model,
but not a direct dependency to the infrastructure/persistence layer. In
addition, you can use
Dependency Injection to isolate the implementation, which is implemented in the infrastructure/
persistence layer using repositories.
For example, the following example with the IOrderRepository interface defines what operations the
OrderRepository class will need to implement at the infrastructure layer. In
the current
implementation of the application, the code just needs to add or update orders to the database, since
queries are split following the simplified CQRS approach.
// Defined at IOrderRepository.cs
public
interface
IOrderRepository : IRepository
{
213
CHAPTER 6 | Tackle Business Complexity in a Microservice with DDD and CQRS Patterns
Order
Add
(Order order);
void
Update
(Order order);
Task
GetAsync
(
int
orderId);
}
// Defined at IRepository.cs (Part of the Domain Seedwork)
Dostları ilə paylaş: