Can Aggregate root entity calls Repository

2019-03-31 07:28发布

问题:

my question is

Can Aggregate root entity have 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 unit testing example for domain driven design ?

回答1:

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...



回答2:

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.



回答3:

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);
    }
}