• This repository has been archived on 17/Mar/2020
  • Stars
    star
    329
  • Rank 123,803 (Top 3 %)
  • Language
    C#
  • License
    Apache License 2.0
  • Created over 7 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Entity Framework Core Second Level Caching Library

Announcing a better Second Level Caching Library!

EFSecondLevelCache.Core

GitHub Actions status

Entity Framework Core Second Level Caching Library.

Second level caching is a query cache. The results of EF commands will be stored in the cache, so that the same EF commands will retrieve their data from the cache rather than executing them against the database again.

Install via NuGet

To install EFSecondLevelCache.Core, run the following command in the Package Manager Console:

Nuget

PM> Install-Package EFSecondLevelCache.Core

You can also view the package page on NuGet.

This library also uses the CacheManager.Core, as a highly configurable cache manager. To use its in-memory caching mechanism, add these entries to the .csproj file:

  <ItemGroup>
    <PackageReference Include="EFSecondLevelCache.Core" Version="2.9.0" />
    <PackageReference Include="CacheManager.Core" Version="1.2.0" />
    <PackageReference Include="CacheManager.Microsoft.Extensions.Caching.Memory" Version="1.2.0" />
    <PackageReference Include="CacheManager.Serialization.Json" Version="1.2.0" />
  </ItemGroup>

And to get the latest versions of these libraries you can run the following command in the Package Manager Console:

PM> Update-Package

Usage

1- Register the required services of EFSecondLevelCache.Core and also CacheManager.Core

namespace EFSecondLevelCache.Core.AspNetCoreSample
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddEFSecondLevelCache();

            // Add an in-memory cache service provider
            services.AddSingleton(typeof(ICacheManager<>), typeof(BaseCacheManager<>));
            services.AddSingleton(typeof(ICacheManagerConfiguration),
                new CacheManager.Core.ConfigurationBuilder()
                        .WithJsonSerializer()
                        .WithMicrosoftMemoryCacheHandle(instanceName: "MemoryCache1")
                        .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMinutes(10))
                        .Build());
        }
    }
}

If you want to use the Redis as the preferred cache provider, first install the CacheManager.StackExchange.Redis package and then register its required services:

// Add Redis cache service provider
var jss = new JsonSerializerSettings
{
    NullValueHandling = NullValueHandling.Ignore,
    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};

const string redisConfigurationKey = "redis";
services.AddSingleton(typeof(ICacheManagerConfiguration),
    new CacheManager.Core.ConfigurationBuilder()
        .WithJsonSerializer(serializationSettings: jss, deserializationSettings: jss)
        .WithUpdateMode(CacheUpdateMode.Up)
        .WithRedisConfiguration(redisConfigurationKey, config =>
        {
            config.WithAllowAdmin()
                .WithDatabase(0)
                .WithEndpoint("localhost", 6379)
                // Enables keyspace notifications to react on eviction/expiration of items.
                // Make sure that all servers are configured correctly and 'notify-keyspace-events' is at least set to 'Exe', otherwise CacheManager will not retrieve any events.
                // See https://redis.io/topics/notifications#configuration for configuration details.
                .EnableKeyspaceEvents();
        })
        .WithMaxRetries(100)
        .WithRetryTimeout(50)
        .WithRedisCacheHandle(redisConfigurationKey)
        .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMinutes(10))
        .Build());
services.AddSingleton(typeof(ICacheManager<>), typeof(BaseCacheManager<>));

2- Setting up the cache invalidation by overriding the SaveChanges method to prevent stale reads:

namespace EFSecondLevelCache.Core.AspNetCoreSample.DataLayer
{
    public class SampleContext : DbContext
    {
        public SampleContext(DbContextOptions<SampleContext> options) : base(options)
        { }

        public virtual DbSet<Post> Posts { get; set; }

        public override int SaveChanges()
        {
            var changedEntityNames = this.GetChangedEntityNames();

            this.ChangeTracker.AutoDetectChangesEnabled = false; // for performance reasons, to avoid calling DetectChanges() again.
            var result = base.SaveChanges();
            this.ChangeTracker.AutoDetectChangesEnabled = true;

            this.GetService<IEFCacheServiceProvider>().InvalidateCacheDependencies(changedEntityNames);

            return result;
        }
    }
}

3- Then to cache the results of the normal queries like:

var products = context.Products.Include(x => x.Tags).FirstOrDefault();

We can use the new Cacheable() extension method:

// If you don't specify the `EFCachePolicy`, the global `new CacheManager.Core.ConfigurationBuilder().WithExpiration()` setting will be used automatically.
var products = context.Products.Include(x => x.Tags).Cacheable().FirstOrDefault(); // Async methods are supported too.

// Or you can specify the `EFCachePolicy` explicitly to override the global settings.
var post1 = context.Posts
                   .Where(x => x.Id > 0)
                   .OrderBy(x => x.Id)
                   .Cacheable(CacheExpirationMode.Sliding, TimeSpan.FromMinutes(5))
                   .FirstOrDefault();

// NOTE: It's better to add the `Cacheable()` method before the materialization methods such as `ToList()` or `FirstOrDefault()` to cover the whole expression tree.

Also AutoMapper's ProjectTo() method is supported:

var posts = context.Posts
                   .Where(x => x.Id > 0)
                   .OrderBy(x => x.Id)
                   .Cacheable()
                   .ProjectTo<PostDto>(configuration: _mapper.ConfigurationProvider)
                   .ToList();

Guidance

When to use

Good candidates for query caching are global site settings and public data, such as infrequently changing articles or comments. It can also be beneficial to cache data specific to a user so long as the cache expires frequently enough relative to the size of the user base that memory consumption remains acceptable. Small, per-user data that frequently exceeds the cache's lifetime, such as a user's photo path, is better held in user claims, which are stored in cookies, than in this cache.

Scope

This cache is scoped to the application, not the current user. It does not use session variables. Accordingly, when retriveing cached per-user data, be sure queries in include code such as .Where(x => .... && x.UserId == id).

Invalidation

This cache is updated when an entity is changed (insert, update, or delete) via a DbContext that uses this library. If the database is updated through some other means, such as a stored procedure or trigger, the cache becomes stale.

More Repositories

1

EFCoreSecondLevelCacheInterceptor

EF Core Second Level Cache Interceptor
C#
635
star
2

iTextSharp.LGPLv2.Core

iTextSharp.LGPLv2.Core is an unofficial port of the last LGPL version of the iTextSharp (V4.1.6) to .NET Core
C#
551
star
3

EPPlus.Core

EPPlus.Core is an unofficial port of the EPPlus library to .NET Core
C#
369
star
4

PdfReport.Core

PdfReport.Core is a code first reporting engine, which is built on top of the iTextSharp.LGPLv2.Core and EPPlus.Core libraries
C#
350
star
5

ASPNETCore2JwtAuthentication

Jwt Authentication without ASP.NET Core Identity
SCSS
298
star
6

OpenCVSharp-Samples

A collection of samples about using OpenCV in .NET applications.
C#
257
star
7

DNTPersianUtils.Core

DNTPersianUtils.Core is a collection of Persian helper extension methods
C#
236
star
8

DNTIdentity

A highly customized sample of the ASP.NET Core Identity
C#
232
star
9

DNTCaptcha.Core

DNTCaptcha.Core is a captcha generator and validator for ASP.NET Core applications
SCSS
205
star
10

GitHubFolderDownloader

It lets you to download a single folder of a repository without cloning or downloading the whole repository.
C#
164
star
11

Process-Proxifier

Using FiddlerCore to add proxy settings to the Windows applications
C#
151
star
12

DNTCommon.Web.Core

DNTCommon.Web.Core provides common scenarios' solutions for ASP.NET Core applications.
C#
130
star
13

PdfReport

PdfReport is a code first reporting engine, which is built on top of the iTextSharp and EPPlus libraries.
C#
91
star
14

EnglishToPersianDictionaries

A collection of English to Persian dictionaries
Java
87
star
15

EFSecondLevelCache

Entity Framework 6.x Second Level Caching Library.
C#
65
star
16

DNTProfiler

DNTProfiler is an EF 6.x and NH 4.x profiler.
C#
59
star
17

PersianBingCalendar

Bing daily wallpaper images with Persian calendar
C#
58
star
18

DNTScanner.Core

DNTScanner.Core is a .NET 4x and .NET Core 2x+ wrapper for the Windows Image Acquisition library.
C#
57
star
19

IdentityServerImageGallery

How to use IdentityServer 4.x with an ASP.NET Core app
C#
55
star
20

JwtWithWebAPI

Creating a RESTful API with authentication using Web API 2.x and JSON Web Tokens
JavaScript
44
star
21

DNTScheduler.Core

DNTScheduler.Core is a lightweight ASP.NET Core's background tasks runner and scheduler
C#
44
star
22

DNTPersianComponents.Blazor

A collection of Persian components for Blazor
SCSS
39
star
23

DNTBreadCrumb.Core

DNTBreadCrumb.Core Creates custom bread crumb definitions, based on Twitter Bootstrap features for ASP.NET Core applications.
SCSS
32
star
24

AspNetIdentityDependencyInjectionSample

ASP.NET Identity Dependency Injection Sample
JavaScript
31
star
25

ASPNETCore2CookieAuthentication

Cookie Authentication without ASP.NET Core Identity 7x
SCSS
31
star
26

angular-template-driven-forms-lab

A collection of tips and tricks about how to use an Angular (2+) app with an ASP.NET Core app.
TypeScript
30
star
27

DNTCaptcha.Blazor

A captcha generator for the Blazor based applications.
SCSS
30
star
28

AutoMapperSamples

Using AutoMapper with Entity Framework.
C#
26
star
29

QueryingInEFCore

Querying in Entity Framework Core
C#
25
star
30

IranianITBloggers

A collection of RSS feeds of Iranian IT bloggers
25
star
31

DNTScheduler

DNTScheduler is a super simple ASP.NET's background tasks runner and scheduler.
C#
24
star
32

MvcPlugin

How to create plugins for ASP.NET MVC 4.x/5.x applications.
C#
22
star
33

SubtitleTools

SubtitleTools is a small utility that helps modifying existing subtitles or downloading new ones
C#
21
star
34

AngularMaterialLab

A collection of tips and tricks about how to use an Angular Material 9x app with an ASP.NET Core app
TypeScript
21
star
35

HotelManagementSample

This is a sample project to demonstrate how to work with EF-Core, Web-API, ASP.NET Core identity, Blazor Wasm and Blazor Server
C#
20
star
36

BlazorWasmDynamicPermissions

Blazor WASM Dynamic Permissions
SCSS
19
star
37

KendoUI-Samples

Using KendoUI with ASP.NET.
JavaScript
16
star
38

Exports

Expotred files of the .NET Tips.
C#
15
star
39

WpfFramework

Using Entity framework code-first and unit of work pattern with WPF applications.
C#
14
star
40

DntConsole

This a .NET 7x console app template
C#
14
star
41

KendoUI.Core.Samples

Using KendoUI with ASP.NET Core
JavaScript
14
star
42

SignalR-Samples

Using SiganlR in ASP.NET applications.
JavaScript
13
star
43

Froala-Sample

Using Froala WYSIWYG Editor with ASP.NET
JavaScript
12
star
44

Dependency-Injection-Samples

.NET Dependency Injection Samples
C#
12
star
45

ElmahEFLogger

Global exceptions logger for Entity Framework 6.x using ELMAH
C#
12
star
46

Solution-Template-Generator

Solution template generator, gets a .SLN file containing multiple projects and then converts it to a .VSIX file
C#
12
star
47

jqGrid-Samples

Using jqGrid with ASP.NET MVC
JavaScript
11
star
48

DNTBreadCrumb

DNTBreadCrumb Creates custom bread crumb definitions, based on Twitter Bootstrap 3.x features
C#
11
star
49

MVC5Angular2

Using AngularJS 2.0 with ASP.NET MVC 5.x
TypeScript
11
star
50

ApiUrlsGenerator

This library will help you to convert your `stringly typed` API URL's to strongly typed ones
C#
8
star
51

Mvc-App-Persian-DatePicker

Using JavaScript PersianDatePicker in ASP.NET applications.
CSS
7
star
52

UoW-Sample

Using multiple databases with EF Code First, UoW & DI patterns.
C#
7
star
53

EFCoreSQLiteFTS

Implementing full-text search with SQLite and EF-Core
C#
7
star
54

AOP-Sample

AOP Samples, mostly using StructureMap & Castle.Core
C#
4
star
55

Silverlight-Persian-DatePicker

Silverlight 4 & 5 Persian DatePicker
C#
3
star
56

MVC-Samples

ASP.NET MVC Step By Step
C#
3
star
57

MVC-Ajax-Form-Upload

Adding file upload support to Ajax.BeginForm
JavaScript
3
star
58

ExplorerPCal

Replacing the default Windows calendar with .NET hooks
C#
3
star
59

ProxyValidator

An automated service for validating free to use proxy servers
C#
2
star
60

RemovePdfLinks

Pdf Links Remover.
C#
1
star
61

Disposable-Email-Address-Detector

Using nameapi.org's API in .NET
C#
1
star
62

OpenAPISwaggerDoc

This is a sample project to show how to use the OpenAPI Swagger in .NET apps
C#
1
star
63

.NET-Persian-Subtitles

Persian subtitles for the various .NET related courses
HTML
1
star
64

OxyPlotWpfTests

An OxyPlot Sample
C#
1
star