Skip to content

Cache filters between requests in the ordinary case #31513

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -75,5 +75,7 @@ public ActionDescriptor()
/// Stores arbitrary metadata properties associated with the <see cref="ActionDescriptor"/>.
/// </summary>
public IDictionary<object, object> Properties { get; set; } = default!;

internal IFilterMetadata[]? CachedResuableFilters { get; set; }
}
}
14 changes: 14 additions & 0 deletions src/Mvc/Mvc.Core/src/Filters/FilterFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,24 @@ public static FilterFactoryResult GetAllFilters(
// Cache the filter items based on the following criteria
// 1. Are created statically (ex: via filter attributes, added to global filter list etc.)
// 2. Are re-usable
var allFiltersAreReusable = true;
for (var i = 0; i < staticFilterItems.Length; i++)
{
var item = staticFilterItems[i];
if (!item.IsReusable)
{
item.Filter = null;
allFiltersAreReusable = false;
}
}

if (allFiltersAreReusable && filterProviders.Length == 1 && filterProviders[0] is DefaultFilterProvider defaultFilterProvider)
{
// If we know we can safely cache all filters and only the default filter provider is registered, we can
// probably re-use filters between requests.
actionDescriptor.CachedResuableFilters = filters;
}

return new FilterFactoryResult(staticFilterItems, filters);
}

Expand All @@ -78,6 +87,11 @@ public static IFilterMetadata[] CreateUncachedFilters(
throw new ArgumentNullException(nameof(cachedFilterItems));
}

if (actionContext.ActionDescriptor.CachedResuableFilters is { } cached)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I dislike this pattern and I also dislike that is not doesn't let you capture the thing that isn't null

{
return cached;
}

// Deep copy the cached filter items as filter providers could modify them
var filterItems = new List<FilterItem>(cachedFilterItems.Length);
for (var i = 0; i < cachedFilterItems.Length; i++)
Expand Down