2

Today, I needed to design an entity which holds a reference to it's aggregate root. In order the make sure that the instance of the entity references the same aggregate root as the one it's contained in, I made some restrictions that only the aggregate root is able to create the entity.

public class Aggregate {
   public int Id { get; }
   public IEnumerable<Entities> Entities { get; }
   public Entity CreateEntity(params);
}

public class Entity {
   public int Id { get; }
   public Aggregate Parent { get; }
}

Suddenly, a very important concept about aggregate struck down on me: Aggregates don't magically appear out of nowhere. There is no such thing as 'new Aggregate(id);' in the DDD world.

So, now I'm asking.. who is responsible for creating them? I know there are factories and such, but considering the identity of an aggregate might be a surrogate generated by the database, wouldn't it be plausible that the repository is responsible for aggregate creation?

public class MyAggregate {
    public int Id { get; private set; }

    protected MyAggregate() {}

    public MyAggregate(int id) {
        Id = id;
    }
}

public interface IMyAggregateRepository {

    MyAggregate Create();
    void DeleteById(int id);
    void Update(MyAggregate aggregate);
    MyAggregate GetById(int id);
    // no Add() method on this layer!
}

private class EfMyAggregateRepository : IAggregateRepository {

    public EfMyAggregateRepository(DbContext context) {
        ...
    }

    public MyAggregate Create() {
        var pto = context.Create<MyAggregate>();
        context.Set<MyAggregate>().Attach(pto);
        return pto;
    }

}

That way, it would be possible for the database (or e.g. EF) to autogenerate a key, maybe defininig validation rules in the repository that apply also as well if the entity is being modified (and updated) etc.

Or do I mix things up now? Is this more the task of a service/factory?

5
  • I put my create methods in a repository mostly because it saves me from having to pass around a factory as well as a repository. Works for me but I certainly don't claim to be a DDD expert.
    – Cerad
    Jan 8, 2015 at 15:32
  • I tend to agree with @MikeSW's answer below. Udi Dahan also has a special perspective on this that may be worth a read : udidahan.com/2009/06/29/dont-create-aggregate-roots Jan 9, 2015 at 8:59
  • @guillaume31 I read that too and found it interesting. However, wouldn't there be a large performance penalty doing so? From what I understand, collections must be loaded first before adding to them.
    – plalx
    Jan 9, 2015 at 13:54
  • @plalx I've never done this (always used Repository.Add()) but maybe you can get away by just adding the new Aggregate Root's ID to a list of ID's, as is the recommended practice for aggregate-to-aggregate relationships. Don't know how the various ORMs would handle that. Jan 9, 2015 at 14:37
  • @guillaume31 Well the recommended practice for aggregate-to-aggregate relationship is to model it from the many-to-one side when you can. Therefore, you do not have any collections.
    – plalx
    Jan 9, 2015 at 16:29

3 Answers 3

7

Repository just abstracts the persistence and while it restores (maybe, perhaps the storage itself does the restoration) an aggregate root, it doesn't creates it. The purpose of a repository is not to create objects.

The purpose of a Factory is to create objects, however a factory is used when the creation is not straightforward (like new myobject() ) and it depends on some rules or you don't know which concrete type to ask for (abstract factory).

About aggregates root must come from somewhere, I disagree. They don't have to , but it's preferred if it makes sense from a semantic point of view. I do " new MyAggregate(id)" all the time, it isn't a problem, there's no need to force things according to some arbitrary rule, just because someone said so. If you have a good reason (design, technical) then do it. If not, don't complicate your life.

8
  • Good to see someone encouraging use of the new keyword. Some SRP zealots take the abolishment of the new keyword too religiously. I'd rather see an occasional new than have a class explosion with specifically made factories everywhere. Jan 9, 2015 at 10:59
  • I agree with all you said, however I find that most aggregegate creationnal code usually finds it's natural home on existing aggregates. E.g. post = discussion.post(msg) rather than post = new Post(discussionId, msg). Having factory method on aggregate roots have several advantages, such as reducing the number of parameters required for the creation and more importantly, better express the domain. However, it obviously may have a negative performance impact since you must load another aggregate, but it's usually negligeable.
    – plalx
    Jan 9, 2015 at 13:48
  • 1
    I find very rarely a reason to have a factory method on a AR to create other AR. Usually one AR doesn't know about others, it depends a lot on the domain you're modeling. And 'loading' another AR!??
    – MikeSW
    Jan 9, 2015 at 19:06
  • @MikeSW It's quite a common practice and is discussed in the Implementing Domain-Driven Design book, which is probably the most notorious book after the blue one, if you want to read about it.
    – plalx
    Jan 10, 2015 at 13:45
  • @plalx I agree if you mean entities. If you mean aggregates, then I agree with MikeSW - why should an aggregate ever be responsible for creating and/or loading another aggregate? Can of worms!
    – Chalky
    Dec 24, 2016 at 5:16
0

Aggregate and Aggregate Roots

In real applications explicit Aggregate implementation is not needed. Aggregate is a collection of related entities bounded with aggregation relation with given one main entity called Aggregate Root.

You just have to decide what entities are aggregate roots and then design your classes and aggregates in appliance with aggregate root encapsulation and other rules.

With this consideration I propose following interfaces and classes

interface IAggregateRoot<TKey> 
{
    TKey Key { get; }
}

//entity which is aggregate root
class Car : IAggregateRoot<int>
{
   int Key { get; }
   Ienumerable<Door> Doors { get; }
}

//other entity, not aggregate root
class Door 
{
   string Colour { get; set; }
}

//generic interface with IAggregateRoot constraint
interface IRepository<TAggregateRoot, TKey> where TAggregateRoot : IAggregateRoot
{
   TAggregateRoot Get(TKey key)
   //other methods
}

Factories and Repositories

Both factories and repositories technically create instances of aggregate roots and other bounded to aggregate entities. Both construct aggregate but have different semantic.

Repository

Repository restores aggregate from persistent storage (considering storage model) and assumes that aggregate is in consistent state, that is aggregate invariants are not violated.

If there is an invariant violation, than Repository have to do some actions as already created aggregate is inconsistent (?!).

Factory

Factory is more like a builder. It constructs aggregate with knowledge of it's invariants. During the aggregate construction aggregate can be in inconsistent state, but as the process of aggregate construction is finished, it have to respect invariants and protect them.

If for some reasons there is the invariant violation factory cannot construct aggregate and drops it.

Sometimes repositories use factories to create instances but in most cases, I consider better to fully separate them.

Example

One example how factory can work.

Assume that the invariant of the class Car is 'Car can have only 2 or 4 doors'.

public interface ICar : IAggregateRoot<int>
{
    int Key { get; }
    IEnumerable<IDoor> Doors { get; }
    SetDoors(IEnumerable<IDoor> doors);
}

public class Car : ICar
{
    //take a look here, it's internal
    internal IList<IDoor> Doors { get; set;}

    public int Key { get; set; }
    public IEnumerable<IDoor> Doors { get { return Doors; } }

    //aggregate root always controls aggregate invariants
    public SetDoors(IEnumerable<IDoor> doors)
    {
        if (doors.Count() != 2 || doors.Count() != 4)
            throw new ApplicationException();
        Doors = doors.ToList();
    }

}

interface IDoor { }

class Door : IDoor { }

//generic interface with IAggregateRoot constraint
interface ICarFactory
{
    ICar CreateCar(int doorsCount)
}

public class CarFactory : ICarFactory
{
    public ICar CreateCar(int doorsCount) 
    {
        if (doorsCount != 2 && doorsCount != 4)
            throw new ApplicationException();

        var car = new Car();
        car.Key = 1;

        car.Doors = new List<IDoor>();
        car.Doors.Add(new Door());
        //now car is inconsistent as it holds just one door
        car.Doors.Add(new Door());
        //now car is consistent
        return car;
     }
 } 

This is artificial example, but sometimes aggregate invariants are too complex to satisfy them always during the construction process.

Now it's assumed that Factory and Aggregate Root have close connections as Factory knows about Car internal fields.

Finally, I think you misunderstand some concepts and recommend you to read Evans DDD book.

EDIT: Probably I miss the fact that MyAggregate is actually MyAggregateRoot in question. But for me it's strange to mix these concepts. Moreover, there on SO was one question with explicit artificial Aggregate class containing all aggregate insides just to show aggregate boundaries. I prefer acceptable notion of AggregateRoot just like at most diagrams I've seen http://ptgmedia.pearsoncmg.com/images/chap10_9780321834577/elementLinks/10fig05.jpg

14
  • I struggled if I should downvote your answer. After reading it twice I decided to do it, because you're making such a mess of the concepts. I know this stuff and you managed to confuse me. Your definition of aggregates is .. special and your example is just complicated for no apparent reason. There is no reason why someone would use a factory when 'new Car(2)' is enough. Also, IMO Car should get all its input/creation data via the constructor.
    – MikeSW
    Jan 8, 2015 at 19:22
  • "If there is an invariant violation, than Repository have to do some actions as already created aggregate is inconsistent (?!)." No, the repository doesn't know about consistency rules. When restored, the object should throw an exception if it's in an invalid state (it shouldn't happen). The repo does nothing.
    – MikeSW
    Jan 8, 2015 at 19:24
  • Additionnal, the IDoor, Door and ICar Car pattern is an anti-pattern in most cases. Do not use interfaces when you cannot think of more than a single concrete class.
    – plalx
    Jan 9, 2015 at 13:30
  • @plalx Is it? I know it's pointless, however I think it might be useful if you e.g. decorate a domain model with an interface and use it as a reference for application and infrastructure models (dtos, ptos). I've never done it, but you could have a IEnumerable on the domain model, but return an ICollection on a dto for Automapper etc. That way, the interfaces never change, but you can swap out the implementation from a technical point of view. Plus, if you ever need refactor your domain, you get an instant response from the compiler about what needs to adapt the changes.
    – xvdiff
    Jan 9, 2015 at 16:45
  • @xvdiff While IEnumerable or IUserRepository can obviously have multiple implementations, IDoor or ICar might not. Having automatically an IWhatever is over engineering if there's no actual reason. I usually abstract services, repositories or other 'utilities' where I don't really care about the implementation at that point. However, when modelling domain objects or simple view models, there's no (or very little, for domain objects) reason to abstract them.
    – MikeSW
    Jan 9, 2015 at 19:11
0

"Suddenly, a very important concept about aggregate struck down on me: Aggregates don't magically appear out of nowhere."

You must understand that it is usually preferred not to new up aggregates directly only to follow the Ubiquitous Language (UL) more closely.

For instance, business experts may say that "site visitors shall be able to register to become customers" and so rather than new Customer(visitorId, ...) you may have something like Customer customer = visitor.register(...).

Using purely technical factories doesn't help in that matter since these aren't part of the UL and would serve a very different goal, such as to simplify the creation process from the client perspective or decouple the client from specific implementations.

"There is no such thing as 'new Aggregate(id);' in the DDD world."

That's actually not true at all. When there's no legitimate domain concept that can create the aggregate (and even if there is), newing up the aggregate directly is just fine.

Introducing an uneeded technical factory just for the sake of avoiding new would only complexify the design.

"considering the identity of an aggregate might be a surrogate generated by the database, wouldn't it be plausible that the repository is responsible for aggregate creation?"

The job of the repository is to abstract away persistence details as well as define an explicit contract for aggregates retrieval, it isin't to create aggregates. Obviously, since aggregates must be returned from queries then their instantiation must happen somewhere in the chain, but it is most likely delegated to antoher component such as a factory, an ORM, etc.

If you need a database generated identity you may however place an operation that returns such identity on the repository. For instance you may have a public int nextIdentity() method on the repository that returns the next value of a database sequence.

Following the Interface Segregation Principle (ISP), you may decide to create a dedicated interface for the task, such as CustomerIdentityGenerator.

1
  • @xvdiff Did you forget your question?
    – plalx
    Apr 7, 2017 at 14:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.