I am quit new to DDD. I have checked the responses for: Can a repository access another by DDD? prior to asking, but could not find any relevant information.
In my application, I have an object which contains another object as a property. I have a repository for the main object, but in order to retrieve the value for the property there is a need to access another repository.
My question is: should the first repository access the second repository, or should the application call the two repositories and merge them;
For instance:
for the two classes:
public class Foo1
{
public int Id { get; set; }
// .... More data
public Foo2 foo2 { get; set; }
}
public class Foo2
{
public int Id { get; set; }
public int Type { get; set; }
}
Should the code look like:
public class Foo1Repository
{
public Foo1 Get() {
return new Foo1();
}
}
public class Foo2Repository
{
public Foo2 Get(int foo1Id)
{
return new Foo2();
}
}
public class Application
{
public void main()
{
Foo1 foo1 = new Foo1Repository().Get();
foo1.foo2 = new Foo2Repository().Get(foo1.Id);
}
}
or more like:
public class Foo1Repository
{
public Foo1 Get() {
Foo2Repository foo2Repository = new Foo2Repository();
Foo1 foo1 = new Foo1();
foo1.foo2 = foo2Repository.Get(foo1.Id);
return foo1;
}
}
public class Foo2Repository
{
public Foo2 Get(int foo1Id)
{
return new Foo2();
}
}
public class Application
{
public void main()
{
Foo1 foo1 = new Foo1Repository().Get();
}
}
Sure, I would appreciate to know if there is any better architecture?
Thanks!
Foo2
seems to exhibit characteristics of an aggregate root, therefore needs its own repository. Then, however, theFoo1
entity must not referenceFoo2
directly, by holding a field of typeFoo2
. InsteadFoo1
must hold a field only forFoo2
's identifier. The second case in my answer explains further. – Risner