Generic Vs Individual Repository for Aggregate Root - domain-driven-design

As I understand, the Bounded Context can have modules, the modules can have many aggregate roots, the aggregate root can have entities. For the persistence, each aggregate root should have a repository.
With the numerous aggregate roots in a large project, is it okay to use a Generic Repository, one for ready only and one for update? Or should have separate repository for each aggregate root which can provide better control.

In a large complex project, I wouldn't recommend using a generic repository since there will most likely be many specific cases beyond your basic GetById(), GetAll()... operations.
Greg Young has a great article on generic repositories : http://codebetter.com/gregyoung/2009/01/16/ddd-the-generic-repository/
is it okay to use a Generic Repository, one for ready only and one for update?
Repositories generally don't handle saving updates to your entities, i.e. they don't have an Update(EntityType entity) method. This is usually taken care of by your ORM's change tracker/Unit of Work implementation. However, if you're looking for an architecture that separates reads from writes, you should definitely have a look at CQRS.

Pure DDD is about making implicit explicit, ie : not using List(), but rather ListTheCustomerThatHaveNotBeSeenForALongTime().
What is at stake here is a technical implementation. From What I know, domain driven design does not provide technical choices.
Generic repository fits well. Your use of this generic repository might not fit the spirit of ddd though. It depends on your domain.

On some of the sample DDD applications that are published on the web, I have seen them have a base repository interface that each aggregate root repository inherits from. I, personally, do things a bit differently. Because repositories are supposed to look like collections to the application code, my base repository interface inherits from IEnumerable so I have:
public interface IRepository<T> : IEnumerable<T> where T : IAggregateRoot
{
}
I do have some base methods I put in there, but only ones that allow reading the collection because some of my aggregate root objects are encapsulated to the point that changes can ONLY be made through method calls.
To answer your question, yes it is fine to have a generic repository, but try not to define any functionality that shouldn't be inherited by ALL repositories. And, if you do accidentally define something that one repository doesn't need, refactor it out into all of the repository interfaces that do need it.
EDIT: Added example of how to make repositories behave just like any other ICollection object.
On the repositories that require CRUD operations, I add this:
void Add(T item); //Add
void Remove(T item); //Remove
T this[int index] { set; } //or T this[object id] { set; } //Update

Thanks for the comments. The approach that I took was separated the base repository interface into ReadOnly and Updatable. Every aggregate root entity will have it's own repository and is derived from Updatable or readonly repository. The repository at the aggregate root level will have it's own additional methods. I'm not planning to use a generic repository.
There is a reason I choose to have IReadOnlyRepository. In the future, I will convert the query part of the app to a CQRS. So the segregation to a ReadOnly interface supertype will help me at that point.

Related

Benefit Of Repository and what is difference between two statements

I'm learning the repository pattern. I've implemented it in a sample project. But I don't know what the main benefit of repository is.
private IStudentRespostiry repository = null;
public StudentController()
{
this.repository = new StudentRepository();
}
public StudentController(IStudentRespostiry repository)
{
this.repository = repository;
}
StudentRepository class can also access the method by creating object of the class.
StudentRepository obj = new StudentRepository();
Anyone have Solid reason for this. One I know in hiding data.
The main reasons for repository people cite are testability and modularity. For testability, you can replace the concrete object with mock one where the repository is used. For modularity you can create different repository, that for example uses different data story.
But I'm highly skeptical of modularity, because repositories are often highly leaky abstractions and changing backed data store is extremely rare. Meaning that something that should be as simple as creating a different instance turns into complete rewrite. Defeating the purpose of repository.
There are other ways to achieve testability with your data store without worrying about leaky abstractions.
As for your code examples. In first case, first constructor is "default" one and second is probably for either IoC or testing with mocks. IMO there should be no "default" one, because it removes the purpose of actually having an IoC.
The second statement allows dependency injection. This means you can use an IoC container to inject the correct implementation.
So for example, in your unit tests you could inject an in memory database (see mocking) while your production code would use an implementation which hits the actual database.

Aggregate Root references other aggregate roots

I'm currently working a lot with DDD, and I'm facing a problem when loading/operating on aggregate roots from other aggregate roots.
For each aggregate root in my model, I also have a repository. The repository is responsible for handling persistence operations for the root.
Let's say that I have two aggregate roots, with some members (entities and value objects).
AggregateRoot1 and AggregateRoot2.
AggregateRoot1 has an entity member which references AggregateRoot2.
When I load AggregateRoot1, should I load AggregateRoot2 as well?
Should the repository for AggregateRoot2 be responsible for this?
If so, is it okay for the entity in AggregateRoot1 to call the repository of AggregateRoot2 for loading?
Also, when I create an association between the entity in AggregateRoot1 to AggregateRoot2, should that be done through the entity, or through the repository for AggregateRoot2?
Hope my question makes sense.
[EDIT]
CURRENT SOLUTION
With help from Twith2Sugars I've come up with the following solution:
As described in the question, an aggregate root can have children that have references to other roots. When assigning root2 to one of the members of root1, the repository for root1 will be responsible for detecting this change, and delegating this to the repository for root2.
public void SomeMethod()
{
AggregateRoot1 root1 = AggregateRoot1Repository.GetById("someIdentification");
root1.EntityMember1.AggregateRoot2 = new AggregateRoot2();
AggregateRoot1Repository.Update(root1);
}
public class AggregateRoot1Repository
{
public static void Update(AggregateRoot1 root1)
{
//Implement some mechanism to detect changes to referenced roots
AggregateRoot2Repository.HandleReference(root1.EntityMember1, root1.EntityMember1.AggregateRoot2)
}
}
This is just a simple example, no Law of Demeter or other best principles/practices included :-)
Further comments appreciated.
I've been in this situation myself and came to a conclusion that it's too much of a head ache to make child aggregates work in an elegant way. Instead, I'd consider whether you actually need to reference the second aggregate as child of the first. It makes life much easier if you just keep a reference of the aggregate's ID rather than the actual aggregate itself. Then, if there is domain logic that involves both aggregates this can be extracted to a domain service and look something like this:
public class DomainService
{
private readonly IAggregate1Repository _aggregate1Repository;
private readonly IAggregate2Repository _aggregate2Repository;
public void DoSomething(Guid aggregateID)
{
Aggregate1 agg1 = _aggregate1Repository.Get(aggregateID);
Aggregate2 agg2 = _aggregate2Repository.Get(agg1.Aggregate2ID);
agg1.DoSomething(agg2);
}
}
EDIT:
I REALLY recommend these articles on the subject: https://vaughnvernon.co/?p=838
This approach have some issues. first, you should have one repository to each aggregate and its done. having one repository that calls another one is a break on this rule. second, a good practice about aggregate relationship is that one root aggregate should communicate with another root aggregate by its id, not having its reference. doing so, you keep each aggregate independent of another aggregate. keep reference in root aggregate only of the classes that compose the same aggregate.
Perhaps the AggregateRoot1 repository could call AggregateRoot2 repository when it's constructing the the AggregateRoot1 entity.
I don't think this invalidates ddd since the repositories are still in charge of getting/creating their own entities.

Does DDD allow for a List to be an Aggregate Root?

I am trying to understand the fundamentals of Domain-driven design. Yesterday I found some code in a project I am working with where a Repository returned a list of Entities, i.e. List getMessages() where Message is an entity (has its own id and is modifiable). Now, when reading about Repositories in DDD they are pretty specific that the Repository should return the Aggregate Root, and that any actions on the aggregate should be done by invoking methods in the Aggregate Root.
I would like to place the List in its own class and then just return that class. But, in my project there is basically no need to do that except for compliance with DDD, since we only show messages, add new ones or remove an existing message. We will never have to remove all messages, so the only methods we would have are, addMessage(...), getMessages(), updateMessage(...) and removeMessage(...) which is basically what our Domain Service is doing.
Any ideas anyone? What is the best practice in DDD when it comes to describe Aggregates and Repositories?
One of the confusing aspects of those new to DDD is repository concept.
Repository:
Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.
A Repository provides the ability to obtain a reference to an Aggregate root. Not Entity, Value Object, but Aggregate root ( i dont agree with "Repository should return the Aggregate Root").
Suggestions:
- One repository per aggregate root
Repository interfaces (e.g. IMessageRepository) reside in the domain model
public interface IMessageRepository()
{
void saveMessage(Message msg);
void removeMessage(Message msg);
Ilist<Messages> getMessages();
}
Repository implementations (e.g. NHibernateMessageRepository if using nhibernate) reside outside the domain
Hope this help!!

Pros and cons of DDD Repositories

Pros:
Repositories hide complex queries.
Repository methods can be used as transaction boundaries.
ORM can easily be mocked
Cons:
ORM frameworks offer already a collection like interface to persistent objects, what is the intention of repositories. So repositories add extra complexity to the system.
combinatorial explosion when using findBy methods. These methods can be avoided with Criteria objects, queries or example objects. But to do that no repository is needed because a ORM already supports these ways to find objects.
Since repositories are a collection of aggregate roots (in the sense of DDD), one have to create and pass around aggregate roots even if only a child object is modified.
Questions:
What pros and cons do you know?
Would you recommend to use repositories? (Why or why not?)
The main point of a repository (as in Single Responsibility Principle) is to abstract the concept of getting objects that have identity. As I've become more comfortable with DDD, I haven't found it useful to think about repositories as being mainly focused on data persistence but instead as factories that instantiate objects and persist their identity.
When you're using an ORM you should be using their API in as limited a way as possible, giving yourself a facade perhaps that is domain specific. So regardless your domain would still just see a repository. The fact that it has an ORM on the other side is an "implementation detail".
Repository brings domain model into focus by hiding data access details behind an interface that is based on ubiquitous language. When designing repository you concentrate on domain concepts, not on data access. From the DDD perspective, using ORM API directly is equivalent to using SQL directly.
This is how repository may look like in the order processing application:
List<Order> myOrders = Orders.FindPending()
Note that there are no data access terms like 'Criteria' or 'Query'. Internally 'FindPending' method may be implemented using Hibernate Criteria or HQL but this has nothing to do with DDD.
Method explosion is a valid concern. For example you may end up with multiple methods like:
Orders.FindPending()
Orders.FindPendingByDate(DateTime from, DateTime to)
Orders.FindPendingByAmount(Money amount)
Orders.FindShipped()
Orders.FindShippedOn(DateTime shippedDate)
etc
This can improved by using Specification pattern. For example you can have a class
class PendingOrderSpecification{
PendingOrderSpecification WithAmount(Money amount);
PendingOrderSpecification WithDate(DateTime from, DateTime to)
...
}
So that repository will look like this:
Orders.FindSatisfying(PendingOrderSpecification pendingSpec)
Orders.FindSatisfying(ShippedOrderSpecification shippedSpec)
Another option is to have separate repository for Pending and Shipped orders.
A repository is really just a layer of abstraction, like an interface. You use it when you want to decouple your data persistence implementation (i.e. your database).
I suppose if you don't want to decouple your DAL, then you don't need a repository. But there are many benefits to doing so, such as testability.
Regarding the combinatorial explosion of "Find" methods: in .NET you can return an IQueryable instead of an IEnumerable, and allow the calling client to run a Linq query on it, instead of using a Find method. This provides flexibility for the client, but sacrifices the ability to provide a well-defined, testable interface. Essentially, you trade off one set of benefits for another.

DDD Repositories and Factories

i've read a blog about DDD from Matt Petters
and according and there it is said that we create a repository (interface) for each entity and after that we create a RepositoryFactory that is going to give instances (declared as interfaces) of repositories
is this how project are done using DDD ?
i mean, i saw projects that i thought that they use DDD but they were calling each repository directly, there was no factory involved
and also
why do we need to create so much repository classes, why not use something like
public interface IRepository : IDisposable
{
T[] GetAll();
T[] GetAll(Expression<Func> filter);
T GetSingle(Expression<Func> filter);
T GetSingle(Expression<Func> filter, List<Expression<Func>> subSelectors);
void Delete(T entity);
void Add(T entity);
int SaveChanges();
}
i guess it could be something with violating the SOLID principles, or something else ?
There are many different ways of doing it. There's is not single 'right' way of doing it. Most people prefer a Repository per Entity because it lets them vary Domain Services in a more granular way. This definitely fits the 'S' in SOLID.
When it comes to factories, they should only be used when they add value. If all they do is to wrap a new operation, they don't add value.
Here are some scenarios in which factories add value:
Abtract Factories lets you vary Repository implementations independently of client code. This fits well with the 'L' in SOLID, but you could also achieve the same effect by using DI to inject the Repository into the Domain Service that requires it.
When the creation of an object in itself is such a complex operation (i.e. in involves much more than just creating a new instance) that it is best encapsulated behind an API.

Resources