Вопрос

We have a complex shopping cart structure. The complexity is in the pricing structure. It takes a considerable number of distinct database entities to calculate all of the pricing. Because of the complexity, we only store small amount of data for each customer's shopping cart, and when we need the cart, we read all of those cart data and also the many pricing parts from the database - (EDIT)AND PUT THE RESULTS INTO A SHOPPING CART OBJECT, COMPLETE WITH TOTALS. This is unfortunately relatively expensive timewise.

Our master site layout (EDIT)GETS THE SHOPPING CART OBJECT and exposes a link to the shopping cart and shows the amount due, if there are any items in the cart.

We have pages that may or may not show other information from the cart. For example, the "About Us" page does not need the cart, but the site layout will still need it.

I set up a global object for the shopping cart. I can access that object from the master site layout. I can also put it into a viewmodel for the page.

So sometimes the master site layout instantiates the shopping cart, and the viewmodel instantiates a shopping cart independently.

(EDIT) SO THE SITE LAYOUT NEEDS THE SHOPPING CART OBJECT FOR EVERY PAGE - AND THE PAGES MAY OR MAY NOT NEED THE SHOPPING CART OBJECT.

The problem: the view may or may not have a shopping cart that it could put into the ViewBag so the master site layout could use it. How can I instantiate the shopping cart object only once in the life cycle?

public class ShoppingCart
{
    // Complex, data intensive calculations upon instantiation
}

public class myViewModel
{
    public ShoppingCart cart {get; set;}
}

In the master site layout:

@{
    ShoppingCart cart = new ShoppingCart(GlobalMemberID);
}

In a page that needs the Shopping Cart:

@model myViewModel
Это было полезно?

Решение

You could store the shopping cart instance into the HttpContext.Items dictionary so that it is available throughout the entire HTTP Request lifecycle and avoid hitting the database twice for the same data.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top