Skip to content

Commit 6b7be11

Browse files
Add UseMemoryCache and EnableServiceProviderCaching documentation (#5116)
Fixes #4855 Fixes #3102 Co-authored-by: AndriySvyryd <6539701+AndriySvyryd@users.noreply.github.com>
1 parent 1721a98 commit 6b7be11

File tree

4 files changed

+61
-2
lines changed

4 files changed

+61
-2
lines changed

entity-framework/core/dbcontext-configuration/index.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
title: DbContext Lifetime, Configuration, and Initialization - EF Core
33
description: Patterns for creating and managing DbContext instances with or without dependency injection
44
author: SamMonoRT
5-
ms.date: 11/07/2020
5+
ms.date: 09/30/2025
66
uid: core/dbcontext-configuration/index
77
---
88

@@ -309,6 +309,8 @@ The following table contains examples of common methods called on `DbContextOpti
309309
| <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.EnableDetailedErrors*> | More detailed query errors (at the expense of performance) | [Logging, Events, and Diagnostics](xref:core/logging-events-diagnostics/index)
310310
| <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.ConfigureWarnings*> | Ignore or throw for warnings and other events | [Logging, Events, and Diagnostics](xref:core/logging-events-diagnostics/index)
311311
| <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.AddInterceptors*> | Registers EF Core interceptors | [Logging, Events, and Diagnostics](xref:core/logging-events-diagnostics/index)
312+
| <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.EnableServiceProviderCaching*> | Controls caching of the internal service provider | [Service Provider Caching](xref:core/testing/advanced-topics#service-provider-caching)
313+
| <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseMemoryCache*> | Configures the memory cache used by EF Core | [Memory Cache Integration](xref:core/performance/advanced-performance-topics#memory-cache-integration)
312314
| <xref:Microsoft.EntityFrameworkCore.ProxiesExtensions.UseLazyLoadingProxies*> | Use dynamic proxies for lazy-loading | [Lazy Loading](xref:core/querying/related-data/lazy)
313315
| <xref:Microsoft.EntityFrameworkCore.ProxiesExtensions.UseChangeTrackingProxies*> | Use dynamic proxies for change-tracking | Coming soon...
314316

entity-framework/core/performance/advanced-performance-topics.md

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
title: Advanced Performance Topics - EF Core
33
description: Advanced performance topics for Entity Framework Core
44
author: roji
5-
ms.date: 9/26/2023
5+
ms.date: 11/21/2025
66
uid: core/performance/advanced-performance-topics
77
---
88
# Advanced Performance Topics
@@ -151,6 +151,9 @@ Note that there is no need to parameterize each and every query: it's perfectly
151151

152152
> [!NOTE]
153153
> EF Core's [metrics](xref:core/logging-events-diagnostics/metrics) report the Query Cache Hit Rate. In a normal application, this metric reaches 100% soon after program startup, once most queries have executed at least once. If this metric remains stable below 100%, that is an indication that your application may be doing something which defeats the query cache - it's a good idea to investigate that.
154+
>
155+
> [!TIP]
156+
> EF Core uses `IMemoryCache` for internal caching of compiled queries and models. You can configure the cache size limit if needed - see [Memory Cache Integration](#memory-cache-integration) for more information.
154157
155158
> [!NOTE]
156159
> How the database manages caches query plans is database-dependent. For example, SQL Server implicitly maintains an LRU query plan cache, whereas PostgreSQL does not (but prepared statements can produce a very similar end effect). Consult your database documentation for more details.
@@ -319,3 +322,19 @@ As with any layer, EF Core adds a bit of runtime overhead compared to coding dir
319322
* Consider disabling thread safety checks by setting `EnableThreadSafetyChecks` to false in your context configuration.
320323
* Using the same `DbContext` instance concurrently from different threads isn't supported. EF Core has a safety feature which detects this programming bug in many cases (but not all), and immediately throws an informative exception. However, this safety feature adds some runtime overhead.
321324
* **WARNING:** Only disable thread safety checks after thoroughly testing that your application doesn't contain such concurrency bugs.
325+
326+
## Memory Cache Integration
327+
328+
EF Core integrates with ASP.NET Core's memory caching infrastructure through `IMemoryCache`. However, this is not used for the internal service provider caching.
329+
330+
EF Core automatically configures `IMemoryCache` with a default size limit of 10240 for internal caching operations such as query compilation and model building. You should call `AddMemoryCache` if you need to change these defaults. For reference, a compiled query has a cache size of 10, while the built model has a cache size of 100.
331+
332+
```csharp
333+
public void ConfigureServices(IServiceCollection services)
334+
{
335+
services.AddMemoryCache(options => options.SizeLimit = 20480); // Custom size limit for EF Core caching
336+
337+
services.AddDbContext<ApplicationDbContext>(options =>
338+
options.UseSqlServer(connectionString));
339+
}
340+
```
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
---
2+
title: Advanced testing topics - EF Core
3+
description: Advanced Entity Framework Core testing topics
4+
author: AndriySvyryd
5+
ms.date: 11/21/2025
6+
uid: core/testing/advanced-topics
7+
---
8+
# Advanced testing topics
9+
10+
This page described some less common topics related to testing EF Core applications.
11+
12+
## EnableServiceProviderCaching
13+
14+
EF Core uses an internal service provider to manage services required for database operations, including query compilation, model building, and other core functionality. By default, EF Core caches these internal service providers to improve performance when multiple `DbContext` instances share the same configuration.
15+
16+
The <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.EnableServiceProviderCaching*> method controls whether EF Core caches the internal service provider:
17+
18+
```csharp
19+
public class ApplicationDbContext : DbContext
20+
{
21+
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
22+
{
23+
optionsBuilder
24+
.EnableServiceProviderCaching(false)
25+
.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Test");
26+
}
27+
}
28+
```
29+
30+
**Default behavior**: Service provider caching is **enabled by default** (`true`). This means:
31+
32+
- Service providers are cached and reused across `DbContext` instances with the same configuration
33+
- Better performance for applications that create many `DbContext` instances
34+
- Lower memory overhead when multiple contexts share configurations
35+
36+
**When to disable caching**: Disabling service provider caching will greatly slow down `DbContext` creation and in the vast majority of cases the default behavior is recommended. If there are issues with incorrect internal services used, then they should be fixed in a different way. But if you are replacing services for testing purposes you could disable service provider caching (`false`) to ensure each test gets a fresh service provider.

entity-framework/toc.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,8 @@
340340
href: core/testing/testing-with-the-database.md
341341
- name: Testing without your production database system
342342
href: core/testing/testing-without-the-database.md
343+
- name: Advanced testing topics
344+
href: core/testing/advanced-topics.md
343345

344346
- name: Performance
345347
items:

0 commit comments

Comments
 (0)