Reputation: 2752
I am trying to get up and running with DDD and there seems to be some limitations imposed by technology stack in my case ASP.Net that make you think about how things will work together. For example let's say I have created a rich class of ShoppingCart and my ShoppingCart has two methods of AddItem(String Sku) and RemoveItem(String Sku). Now I might have a lot of logic in these two methods with a lot of my business rules validation.
What happens when I want to bind my ShoppingCart to the UI using ASP.Net MVC? Ideally I would like to call the AddItem and RemoveItem methods when the user adds or remove an item on the UI so that I can validate all the rules, but normally we bind the UI to View Models (POCO classes). Thus when the user saves the cart from UI I will get a list of POCO classes that I now need to map to my actual business object. Should I iterate over each item and track it from existing data and call AddItem and RemoveItem methods now?
In this case I need to keep an instance of my domain object in memory for that user so that I can perform operations on it. Even then I will have bulk of logic in controller to decide which methods to call on the Business object.
The more I am thinking down these lines the more confusing it gets because the problem would not happen on let's say Winforms, where you can easily call the respective methods on the Domain object from various event.
What am I missing in this whole picture to make DDD work like it should?
Upvotes: 0
Views: 559
Reputation: 4405
Typically, adding and removing resources would be an http POST call. So, the method on your controller handling this call would receive a model of the request to add or remove an item to the cart. For example:
public class AddItemToCartRequest
{
public string CartId { get; set; }
public string ItemId { get; set; }
}
public class SomeController : Controller
{
// Reference to some sort of repository/data store for shopping carts
private Carts carts;
// Reference to some sort of repository/data store for store items.
private Items items;
public SomeController(Carts carts, Items items)
{
this.carts = carts;
this.items = items;
}
[HttpPost]
public ActionResult AddItem(AddItemToCartRequest request)
{
var cart = carts.GetCart(request.CartId);
var item = items.GetItem(request.ItemId);
cart.AddItem(item);
carts.Save(cart);
// Redirect to action showing the "item added" or whatever.
}
}
The idea is that you do not pass rich domain models back and forth to the view. You pass classes that are models of the views and requests that you are using. On each request, you would fetch domain model instances from a repository/data store (i.e, the carts and items fields in the example). The request data only need to specify identifiers of the domain model instances to fetch.
Upvotes: 1