I think (just a thought, nothing concrete ) that the problem is BusinessManager will try to access the HttpContext which will be shared between the threads. even if you don't have that kind of problem you might run into other (HttpContext is not thread safe IIRC).
Why do you need to load the contacts in parallel? Can you show your code code GetDiscountedPrice(String code) ?
Hi Quan,
The shortened version of Project.Commerce.Core.Prices.Services.PricingService.GetDiscountedPrice(String code)
public IPriceValue? GetDiscountedPrice(string code)
{
// (skipped) getting contentReference from code
var currentMarket = _currentMarket.GetCurrentMarket();
var discountedPrices = _promotionEngine.GetDiscountPrices(new []{contentReference}, currentMarket, currentMarket.DefaultCurrency).ToList();
// (skipped) more logic
return priceValue;
}
And the _promotionEngine.GetDiscountPrices
is just a call to the standard EPiServer.Commerce.Marketing.IPromotionEngineExtensions.GetDiscountPrices
.
We don't use the contacts at all (in this scenario), but calling the IPromotionEngineExtensions.GetDiscountPrices
calls internally loading contact with BusinessManager.Load
and that's where the exception occurs. I tried to go down the chain to isolate what exactly is causing exception, that's why I focused on BusinessManager.Load
.
I think you can preload the contact using CustomerContext.Current.GetContactById, which would cache the contact and avoid calling to BusinessManager.Load
Not every API is meant to be run in parallel
Hi,
As in title - the
BusinessManager.Load
throwsNullReferenceException
when called withinIBackgroundContext
.The
BusinessManager.Load
method is called byIPromotionEngineExtensions.GetDiscountPrices
within a service, that we'd like to parallelize usingIBackgroundContext
andTask.WhenAll
.On the other hand, if we're not using
IBackgroundContext
, we're getting errors mentioned in:https://world.optimizely.com/blogs/Johan-Bjornfot/Dates1/2023/8/parallel-tasks-and-backgroundcontext/
Is the there a way to utilize the
GetDiscountPrices
(and by extent theBusinessManager.Load
) withinIBackgroundContext
?Code to reproduce:
The stack trace of above example:
The stack trace of real-world example (anonimized):