I used to deal with simple apps that have Service Layer containing all of the business logic. In Domain Driven Design it's common to keep business logic in a rich model.
Watched a tutorial by Pluralsight in which they mention Repositories and noticed that a repo normally contains basic CRUD operations (create, update, fetch & remove entity). Nothing much was explained with regard to Entity Framework.
Entity Framework 6 & Entity Framework Core already provide Repository/UoW out of the box. I'm wondering if we can omit creating Repository Layer in this case?
So, how I imagine the app without a separate Repository layer...
My understanding is:
For example we have Customer
model as an Aggregate Root (rich domain model). And that model has one-to-many relation ICollection<Payment> Payments
. Plus, according to DDD - we keep our logic inside the model - so we have MakePayment
method.
The code will be as follows:
public class Customer
{
public virtual ICollection<Payment> Payments { get; set; }
// ... other properties/collections
public void MakePayment(decimal amount)
{
this.Payments.Add(new Payment() { Amount = amount });
}
}
With Entity Framework we can eagerly load the entire tree with the result Customer
already has all their Payments
mapped.
(say, we deal with an ASP.NET WebAPI app)
So, in order to make a payment, I imagine, we do the following:
in our controller / service we fetch a customer (for example by
id
)then follows the code
customer.MakePayment(10);
after that we call
dbContext.SaveChanges()
methodDbContext
tracks the changes and stores the payment - Bingo!
Is my understanding correct?
Regarding Service Layer:
Would it be okay to have Service Layer with DDD in such a web app?
I still think keeping the code in controller isn't necessarily the right thing to do (even with DDD) as long as e.g. part of functionality MAY BE required in a WPF app - so we can use Service Layer with it.
Seems like the most optimal approach, doesn't it?