DDDD: Event data - domain-driven-design

I'm trying to get my head around DDDD in Greg Young's style.
There is much talk about how to implement DDDD with CQRS+EventSourcing and there are some sample implementations ... and altogether it can be quite confusing...
In Gregs view aggregates don't have getters or setters - just state-changing methods which emit an corresponding event.
Basicly a event decribes a state-transitions that happend in the past. It's data describes what changed.
Some say, that this data can be "enriched" by additional data.
Where can this additional data come from?
i.e. I have User and Usergroup - both aggregate roots (can exist independently, have identity). User has a method called AddToUsergroup.
public class User : AggregateRoot
{
// ...
public void AddToUsergroup(Usergroup usergroup)
{
// validate state
RaiseEvent(new UserJoinedUsergroup(this.Id, usergroup.Id));
}
// ...
}
public class Usergroup : AggregateRoot
{
private string _displayName;
// ...
public void ChangeDisplayName(string displayName)
{
// validate state
RaiseEvent(new DisplayNameChanged(this.Id, displayName));
}
public void Apply(DisplayNameChanged e)
{
this._displayName = e.DisplayName;
}
// ...
}
If I would like to "enrich" the event with the name of the Usergroup (for debug reasons or something like this), how would I do that?
getters are nonexistent
internal state of usergroup is inaccessible
Injecting such things as repositories into User is not allowed (am I right here?!?), like
Read-side repository
Event-store repository
Bottomline questions:
Can Should something like repositories be injected to aggregate roots?
Should a event only use data available through parameters and internal state of the aggregate?
Should events only contain the minimum data describing the state-change?
And (little off-topic but the sample is here)
Should AddToUsergroup take an Guid instead of an full aggregate root?
Looking forward to your answers!
Lg
warappa

Should something like repositories be injected to aggregate roots?
No and there is no need to in this case. It can be appropriate to pass a domain service to a behavioral method on an aggregate, but again, not needed in this case.
Should a event only use data available through parameters and internal
state of the aggregate?
Yes, the original domain event should be such that it can be easily built by the aggregate and can be replayed in a deterministic fashion.
Should events only contain the minimum data describing the
state-change?
Yes. However, to address requirements of external subscribers, this is where content enricher comes into play. To dispatch a domain event externally, it is first committed to the event store then you can dispatch in the same tx or have an out of process mechanism which publishes events externally. At the point of publishing externally, you will normally use a different contract for the message since subscribers may need more than what is on the domain event itself. In this case, you need the user group name. The publisher, then, can pull up the user group name and place that data into the enriched event. This publisher can have access to a read-model repository for user groups which would allow it to retrieve the name.
Should AddToUsergroup take an Guid instead of an full aggregate root?
Yes. Passing the entire aggregate may not be possible and also creates the illusion that something other than the ID may be used, which should not be the case.

Related

How and when to hydrate domain objects in the CQRS command stack

Suppose I have a command that saves an application Role along with some application Permissions. My roles and permissions have (or will have) business rules, so I'll use domain objects:
class Role {
...
IEnumerable<Permission> Permissions { ... }
AddPermission(...)
...
}
class Permission {
...
int ID { ... }
string Foo { ... }
string Bar { ... }
string Baz { ... }
}
When I'm saving a Role, I need a full Role object and will probably receive everything I need from the presentation layer. I do not need full Permission objects, though, because I only need to associate their ID with the Role. I don't need the Foo, Bar, and Baz properties.
When I'm saving a Permission, I obviously need the full Permission object.
My Question: What is the right way to handle that Permission object? If I only have one Permission class, then, when I'm saving a Role, I will either:
Have to query/hydrate full Permission objects from the database so the Role has legitimate Permission objects in its collection, or
Attach incomplete Permission objects (IDs only) to avoid the trip to the database.
Option #1 sounds like the kind of command/query complexity CQRS aims to avoid, and #2 sounds like an invalid object floating around--I don't even want to be able to create invalid objects, much less use them.
I could also create a PermissionSummary class and the full Permission class derives from it. I've done this before, and it inevitably leads to a creep of properties from the "full" class up to the "summary" class.
Batavia's response to CQRS is great and as I have no experience with that pattern Ill try and answer the 'what do I save' question.
The answer to this one depends strongly on your Model design and the proposed behavior of the Permission entities. DDD does not work without a strong knowledge of the business domain.
Having said that I can think of 3 scenarios:
1) Permissions are immutable and Roles get changed. In this scenario Role becomes the aggregate root and the collection of Permissions in re-hydrated on each fetch. The properties and methods of each Permissions entity is available to Role entity enabling operations like
partial class role() {
public enumAccessType AccessToAction(enumAction action) {
foreach(var p in Permissions)
if p.HasFullAccess(action) return enumAccesssType.Full;
foreach(var p in Permissions)
if p.HasLimitedAccess(action) return enumAccesssType.Restricted;
return enumAccesssType.None;
}
}
There is a Permission repository for saving new Permissions and a Role Repository for maintaining the roles and the role_Permission tables
NOTE: Just because the domain object has the full PERMISSION objects doesn't mean that the persistence layer needs to update the PERMISSION table for each of the permissions added. The RoleRepository should only update ROLE (roleId, roleName) and ROLE_PERMISSION (roleId, permissonId) tables.
2) Permissions are mutable But roles are static. In this situation is may make more sense for your model to have Permission as the Aggregate root and a collection of Roles as role is just a bucket for grouping Permissions:
class Permission {
Ienumerable<RoleId> Roles {get;private set;}
PermissionId ID { ... }
string Foo { ... }
string Bar { ... }
}
Again there is Permission repository for saving new Permissions and maintaining the Permission-Role relations. The Role Repository just handles roles.
3) Roles and Permissions change all the time - your security requirement is complex and will difficult for most end users to comprehend. Bring in the Domain Expert to explain how Role and Permissions relate and affect the rest of the system and WHY the have to be so flexible. Look at the why and try and identify processes or behavior that may be incorrectly being forced into a roles-permissions pattern. This will probably require its own bounded context and services to work.
It helps to remembers 'Database Tables' != 'DDD Entities' != 'User Interface'. At first blush it looks like your coming at this from a database design point of view rather than the domain behaviour point of view.
A big 'Am I Doing This Right' is this check: If I save changes to one entity , do I need to reload any other entities that reference that original entity in order for those other entities to work? If the answer is yes then you need to revisit your model.
so when using CQRS i think the answer is neither.
I think it's important to differentiate between DDD and CQRS.
When saving a role (In the CQRS pattern) you would be sending a "RoleChangeRequest" command to your backend. This would then raise a RoleChangeRequested event. (this could be done by a domain service, possibly even by the domain layer itself). This event would be handled by your database layer but this event would look more closely to this
class RoleChangeRequested {
IEnumerable<int> PermissionIds {....}
string name {....}
}
The key here is that in raising the event that would save your data you only need to know about the Id's of the permissions. There is no need to either query permissions (ok, maybe you want some check that they actually exist. but a foreign key relation could handle this). or to attach incomplete objects.
NOTE: In just this example CQRS is going to make your application a lot more complex. CQRS is weapons-grade architecture and should be handled with extreme caution. Now why would you want to use CQRS, that's because your next requirement is to make a full and guaranteed audit trail of all your role and or permission changes. This is just another event handler to the same events. And you could even have an event handler to the generic ievent interface and then you are guaranteed that you audit every event being raised in the application. That you get (almost) for free and is why CQRS can be a benifit.

Should I add item using repository pattern or a create event if I am using domain events?

I am trying to understand the Domain Event pattern illustrated by Udi Dahan with regard to adding new domain entities in a certain situation.
Now normally with entities I would create them and then add them via repository. I assume I would still do this?
My example is we normally add assets to the system. Like this:
var asset= new Asset();
/*bunch of prop setting*/
_assetRepository.Add(asset);
However asset creation is an event that we want to follow certain processes as a result of. Therefore it was suggested by developer we no longer need to do this as it could be handled by domain event:
var asset= new Asset();
/*bunch of prop setting*/
asset.Create(location);
Now a create method would raise an event and be handled by a create event handler that basically just inserts it into the repo and does some other stuff email the warehouse manager of the create location etc.
However having a create event on the asset looks pretty active record to me. However in the domain people talk about new assets being created. So we were not sure.
Thoughts?
The created domain event should be raised in the constructor of the Asset class because that is when that particular entity is created. In your current implementation, this would be erroneous because the Asset entity provides a parameterless constructor. Instead, create a constructor which has all required properties as parameters thereby preventing creation of an Asset entity in an inconsistent state. It could look like this:
public class Asset
{
public Asset(string prop1, decimal prop2)
{
this.Prop1 = prop1;
this.Prop2 = prop2;
DomainEvents.Raise(new AssetCreated(prop1, prop2));
}
public string Id { get; private set; }
public string Prop1 { get; private set; }
public decimal Prop2 { get; private set; }
}
You still have to persist the entity using the repository after creating it. This can be problematic because the handlers for the AssetCreated cannot reference its ID since it is not yet assigned when they are notified. If using event sourcing, then the creation event would be explicitly stored in the underlying event store.
I've been struggling for this problem for quite a long time. But no good solution. I think,
A domain event shouldn't be published or handled before the aggregate it belongs to being successfully persisted
It's not the application layer's responsibility to publish any domain events
So far, I think the best approach is to take advantage of AOP. We can "fire" events in the aggregate, but instead of dispatching them instantly, we keep it in a queue, and really dispatch it after the corresponding transaction successes. We can define a custom #Transactional interceptor to achieve this, thus keeping the app service from knowning any concept of "event publishing".

Domain Driven Design: Repository per aggregate root?

I'm trying to figure out how to accomplish the following:
User can have many Websites
What I need to do before adding a new website to a user, is to take the website URL and pass it to a method which will check whether the Website already exist in the database (another User has the same website associated), or whether to create a new record. <= The reason for this is whether to create a new thumbnail or use an existing.
The problem is that the repository should be per aggregate root, which means I Cant do what I've Explained above? - I could first get ALL users in the database and then foreach look with if statement that checks where the user has a website record with same URL, but that would result in an endless and slow process.
Whatever repository approach you're using, you should be able to specify criteria in some fashion. Therefore, search for a user associated with the website in question - if the search returns no users, the website is not in use.
For example, you might add a method with the following signature (or you'd pass a query object as described in this article):
User GetUser(string hasUrl);
That method should generate SQL more or less like this:
select u.userId
from User u
join Website w
on w.UserId = u.UserId
where w.Url = #url
This should be nearly as efficient as querying the Website table directly; there's no need to load all the users and website records into memory. Let your relational database do the heavy lifting and let your repository implementation (or object-relational mapper) handle the translation.
I think there is a fundamental problem with your model. Websites are part of a User aggregate group if I understand correctly. Which means a website instance does not have global scope, it is meaningful only in the context of belonging to a user.
But now when a user wants to add a new website, you first want to check to see if the "website exists in the database" before you create a new one. Which means websites in fact do have a global scope. Otherwise anytime a user requested a new website, you would create a new website for that specific user with that website being meaningful in the scope of that user. Here you have websites which are shared and therefore meaningful in the scope of many users and therefore not part of the user aggregate.
Fix your model and you will fix your query difficulties.
One strategy is to implement a service that can verify the constraint.
public interface IWebsiteUniquenessValidator
{
bool IsWebsiteUnique(string websiteUrl);
}
You will then have to implement it, how you do that will depend on factors I don't know, but I suggest not worrying about going through the domain. Make it simple, it's just a query (* - I'll add to this at the bottom).
public class WebsiteUniquenessValidator : IWebsiteUniquenessValidator
{
//.....
}
Then, "inject" it into the method where it is needed. I say "inject" because we will provide it to the domain object from outside the domain, but .. we will do so with a method parameter rather than a constructor parameter (in order to avoid requiring our entities to be instantiated by our IoC container).
public class User
{
public void AddWebsite(string websiteUrl, IWebsiteUniquenessValidator uniquenessValidator)
{
if (!uniquenessValidator.IsWebsiteUnique(websiteUrl) {
throw new ValidationException(...);
}
//....
}
}
Whatever the consumer of your User and its Repository is - if that's a Service class or a CommandHandler - can provide that uniqueness validator dependency. This consumer should already by wired up through IoC, since it will be consuming the UserRepository:
public class UserService
{
private readonly IUserRepository _repo;
private readonly IWebsiteUniquenessValidator _validator;
public UserService(IUserRepository repo, IWebsiteUniquenessValidator validator)
{
_repo = repo;
_validator = validator;
}
public Result AddWebsiteToUser(Guid userId, string websiteUrl)
{
try {
var user = _repo.Get(userId);
user.AddWebsite(websiteUrl, _validator);
}
catch (AggregateNotFoundException ex) {
//....
}
catch (ValidationException ex) {
//....
}
}
}
*I mentioned making the validation simple and avoiding the Domain.
We build Domains to encapsulate the often complex behavior that is involved with modifying data.
What experience shows, is that the requirements around changing data are very different from those around querying data.
This seems like a pain point you are experiencing because you are trying to force a read to go through a write system.
It is possible to separate the reading of data from the Domain, from the write side, in order to alleviate these pain points.
CQRS is the name given to this technique. I'll just say that a whole bunch of lightbulbs went click once I viewed DDD in the context of CQRS. I highly recommend trying to understand the concepts of CQRS.

Can Aggregate root entity calls Repository

Is it possible for an Aggregate root entity to have a method in which it will call a Repository?
I know it should not but want to get confirmed as Eric's book is also not saying anything clearly :(
one more thing where can I get a unit testing example for domain-driven design?
This is a bit of a religious question.
Some see no problem with this, while others might believe it is heresy to do so.
While I've normally always kept my Repository away from my Domain Model (and had an upstream service object deal with the Repository), I have had a project that "required" having the Repository accessable from the Domain Model.
This was due to the Domain object needing to retrieve specific data based on business logic => using specification objects/Linq to nHibernate (the responsibility and knowledge of how to filter data belonged to that Domain Object) and/or performance reasons.
A caveat around doing this is how to get the reference to the Repository to the Domain object - in that case I utilized Constructor injection with an IOC tool.
Whether you should do this or not really depends on your solution/use case/technologies being used etc...
Can? -Yes.
Should? -No.
All answers are however context-sensitive, and you don't provide yours.
A generic advise would be to look for a "service" or "specification" type.
Behavior IS-WHAT-IT-IS. Eric calls a Repository like utility from a Brokerage Account entity called, "QueryService". He mentions that it's not a good design for a real project. So what do you do?
public class Clerk
{
public Clerk()
{
}
//Store Report in Database
public void File(Report);
{
ReportRepository.Add(Report);
}
}
You could do that, but it's probably best to tell the Clerk which Repository to use.
public class Clerk
{
private IReportRepository _reportRepository;
public Clerk(IReportRepository ReportRepository)
{
this._reportRepository = ReportRepository
}
//Store Report in Database
public void File(Report);
{
this._reportRepository.Add(Report);
}
}

Getting Additional Data for a Domain Entity

I have a domain Aggregate, call it "Order" that contains a List of OrderLines. The Order keeps track of the sum of the Amount on the Order Lines. The customer has a running "credit" balance that they can order from that is calculated by summing the history of their database transactions. Once they use up all the money in the "pool" they can't order any more products.
So every time a line is added to the order, I need to get to check how much is left in the pool and if the order pushes them over it. The amount in the pool is continually changing because other related customers are continually using it.
The question is, thinking in terms of DDD, how do I get that amount since I don't want to pollute my Domain Layer with DataContext concerns (using L2S here). Since I can't just query out to the database from the domain, how would I get that data so I can validate the business rule?
Is this an instance where Domain Events are used?
Your Order aggregate should be fully encapsulated. It therefore needs to be able to determine whether it's valid to add an item, i.e. whether or not the customer credit is exceeded. There are various ways to do this but they all depend on the Order repository returning a specific aggregate that knows how to do this particular thing. This will probably be a different Order aggregate from one you'd use for satisfying orders, for example.
You have to recognise, then capture in code, the fact that you're expecting the order to fulfil a particular role in this case, i.e. the role of adding additional line items. You do this by creating an interface for this role and a corresponding aggregate that has the internal support for the role.
Then, your service layer can ask your Order repository for an order that satisfies this explicit role interface and the repository thus has enough information about what you need to be able to build something that can satisfy that requirement.
For example:
public interface IOrder
{
IList<LineItem> LineItems { get; }
// ... other core order "stuff"
}
public interface IAddItemsToOrder: IOrder
{
void AddItem( LineItem item );
}
public interface IOrderRepository
{
T Get<T>( int orderId ) where T: IOrder;
}
Now, your service code would look something like:
public class CartService
{
public void AddItemToOrder( int orderId, LineItem item )
{
var order = orderRepository.Get<IAddItemsToOrder>( orderId );
order.AddItem( item );
}
}
Next, your Order class that implements IAddItemsToOrder needs a customer entity so that it can check the credit balance. So you just cascade the same technique by defining a specific interface. The order repository can call on the customer repository to return a customer entity that fulfils that role and add it to the order aggregate.
Thus you'd have a base ICustomer interface and then an explicit role in the form of an ICustomerCreditBalance interface that descends from it. The ICustomerCreditBalance acts both as a marker interface to your Customer repository to tell it what you need the customer for, so it can create the appropriate customer entity, and it has the methods and/or properties on it to support the specific role. Something like:
public interface ICustomer
{
string Name { get; }
// core customer stuff
}
public interface ICustomerCreditBalance: ICustomer
{
public decimal CreditBalance { get; }
}
public interface ICustomerRepository
{
T Get<T>( int customerId ) where T: ICustomer;
}
Explicit role interfaces give repositories the key information they need to make the right decision about what data to fetch from the database, and whether to fetch it eagerly or lazily.
Note that I've put the CreditBalance property on the ICustomerCreditBalance interface in this case. However, it could just as well be on the base ICustomer interface and ICustomerCreditBalance then becomes an empty "marker" interface to let the repository know that you're going to be querying the credit balance. It's all about letting the repository know just what role you want for the entity it returns.
The final part which brings this all together, as you mentioned in your question, is domain events. The order can raise a failure domain event if the customer's credit balance would be exceeded, to notify the service layer that the order is invalid. If the customer has enough credit, on the other hand, it can either update the balance on the customer object or raise a domain event to notify the rest of the system that the balance needs to be reduced.
I've not added the domain event code to the CartService class since this answer is already rather long! If you want to know more about how to do that, I suggest you post another question targeting that specific issue and I'll expand on it there ;-)
In such a scenario, I off-load responsibility using events or delegates. Maybe the easiest way to show you is with some code.
Your Order class will have a Predicate<T> that is used to determine if the customer's credit line is big enough to handle the order line.
public class Order
{
public Predicate<decimal> CanAddOrderLine;
// more Order class stuff here...
public void AddOrderLine(OrderLine orderLine)
{
if (CanAddOrderLine(orderLine.Amount))
{
OrderLines.Add(orderLine);
Console.WriteLine("Added {0}", orderLine.Amount);
}
else
{
Console.WriteLine(
"Cannot add order. Customer credit line too small.");
}
}
}
You will probably have a CustomerService class or something like that to pull the available credit line. You set the CanAddOrderLine predicate before adding any order lines. This will perform a check of the customer's credit each time a line is added.
// App code.
var customerService = new CustomerService();
var customer = new Customer();
var order = new Order();
order.CanAddOrderLine =
amount => customerService.GetAvailableCredit(customer) >= amount;
order.AddOrderLine(new OrderLine { Amount = 5m });
customerService.DecrementCredit(5m);
No doubt your real scenario will be more complicated than this. You may also want to check out the Func<T> delegate. A delegate or event could be useful for decrementing the credit amount after the order line is placed or firing some functionality if the customer goes over their credit limit in the order.
Good luck!
In addition to the problem of getting the "pool" value (where I would query the value using a method on an OrderRepository), have you considered the locking implications for this problem?
If the "pool" is constantly changing, is there a chance that someone elses transaction creeps in just after your rule passes, but just before you commit your changes to the db?
Eric Evans refers to this very problem in Chapter 6 of his book ("Aggregates").

Resources