jeudi 8 janvier 2015

Repositories as factories?

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?


Aucun commentaire:

Enregistrer un commentaire