Access cart context in event


I want to perform some changes to the cart when the CartUpdated event is fired, for example, add a fee depending on if the cart contains a specific item. However, to add/update an item to the cart, I (guess) I have to use the methods in the CartContext?

We have products that should apply a fee, depending on the product type, and I can’t find a better way to this than listening to the CartUpdated event? I could use the same check in the “add” endpoint, but we have multiple ways to add an item to the cart, that doesn’t necessarily use the “add” endpoint in the CartController.

Litium version: 8.2.1

But adding with an event would loose the context of the person even if you were to find the cart context in an event, so you would not have an updated cart in the user context. And would have to re fetch the cart and hope that it’s updated.

Can you create a service for “Add” that you use everywhere you add something to the cart?
Or every time, before you build the cart you make your check and uppdate with what you need.

But to answer a part of your question, you can save the cart with:


And set the context again with

await context.HttpContext.SwitchCartContextAsync(cartSystemId);

That way, I suppose you could update the cart in an event. :thinking:

Yeah that’s true… Good catch!

I thought about using a service for each add, but using an event would feel safer as there’s no chance to forget using that service. If someone writes some code that adds an item to the cart without using that service, we would have a problem… :smiley:

I think I will go with the service solution. Thanks!

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.