Skip to content

Commit 1195a6c

Browse files
Move MemoryCache creation outside lambda; clarify DI cache sharing
Create the MemoryCache instance outside the AddDbContext lambda to avoid creating multiple instances. Add note that the DI-based approach shares the cache between EF Core and other services. Agent-Logs-Url: https://github.com/dotnet/EntityFramework.Docs/sessions/578f8c2e-3eba-404b-8c17-ec1293337639 Co-authored-by: AndriySvyryd <6539701+AndriySvyryd@users.noreply.github.com>
1 parent a2e7393 commit 1195a6c

1 file changed

Lines changed: 4 additions & 2 deletions

File tree

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -331,14 +331,16 @@ EF Core uses `IMemoryCache` for internal caching operations such as query compil
331331
If you need to change the default cache size limit, use <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseMemoryCache*> to provide a custom `IMemoryCache` instance:
332332

333333
```csharp
334+
var memoryCache = new MemoryCache(new MemoryCacheOptions { SizeLimit = 20480 });
335+
334336
services.AddDbContext<ApplicationDbContext>(options =>
335337
{
336-
options.UseMemoryCache(new MemoryCache(new MemoryCacheOptions { SizeLimit = 20480 }));
338+
options.UseMemoryCache(memoryCache);
337339
options.UseSqlServer(connectionString);
338340
});
339341
```
340342

341-
Alternatively, if you register a custom `IMemoryCache` via `AddMemoryCache` in DI, you can resolve it from the service provider:
343+
Alternatively, if you register a custom `IMemoryCache` via `AddMemoryCache` in DI, you can resolve it from the service provider. Note that this shares the cache between EF Core and any other services that use `IMemoryCache`, so the size limit should account for all consumers:
342344

343345
```csharp
344346
services.AddMemoryCache(options => options.SizeLimit = 20480);

0 commit comments

Comments
 (0)