Skip to content

Commit

Permalink
TermsPart.Record usage made before the delegate to avoid accessing a …
Browse files Browse the repository at this point in the history
…scope which is already disposed. (#8766)
  • Loading branch information
AndreaPiovanelli authored Mar 15, 2024
1 parent 50d416c commit 2d7ce45
Showing 1 changed file with 12 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,22 @@ private void InitializerTermsLoader(TermsPart part) {
var queryHint = new QueryHints()
.ExpandRecords("ContentTypeRecord", "CommonPartRecord", "TermsPartRecord");

// Get TermRecordIds for each field before the delegate inside the for iterator.
// This avoids the TermsPart.Record lifetime scope to be disposed when executed, since ContentPart.Record is a LazyField.
var groupedRecordIds = part.Record.Terms
.GroupBy(tci => tci.Field)
.ToDictionary(g => g.Key,
g => g.Select(tci => tci.TermRecord.Id).ToArray());

foreach (var field in part.ContentItem.Parts.SelectMany(p => p.Fields).OfType<TaxonomyField>()) {
var tempField = field.Name;
field.TermsField.Loader(() => {
var fieldTermRecordIds = part.Record.Terms.Where(t => t.Field == tempField).Select(tci => tci.TermRecord.Id);
// Using context content item's ContentManager instead of injected one to avoid lifetime scope exceptions in case of LazyFields.
var terms = part.ContentItem.ContentManager.GetMany<TermPart>(fieldTermRecordIds, VersionOptions.Published, queryHint);
var terms = Enumerable.Empty<TermPart>();
if (groupedRecordIds.TryGetValue(tempField, out var fieldTermRecordIds)) {
// Using context content item's ContentManager instead of injected one to avoid lifetime scope exceptions in case of LazyFields.
terms = part.ContentItem.ContentManager.GetMany<TermPart>(fieldTermRecordIds, VersionOptions.Published, queryHint);
}

return terms.ToList();
});
}
Expand Down

0 comments on commit 2d7ce45

Please sign in to comment.