Open sandboxFocusImprove this doc

Using In-Memory Cache

For local, in-memory caching, PostSharp offers two different back-end classes:

  • MemoryCachingBackend relies on MemoryCache and can only be used with projects targeting the .NET Framework v4.5 and later.

  • MemoryCacheBackend relies on Microsoft.Extensions.Caching.Memory.IMemoryCache and requires .NET Standard 2.0, therefore it can be used in .NET Core applications too.

In-memory caching for .NET Framework

To use the MemoryCache class to store cached values in memory, assign an instance of a MemoryCachingBackend class to DefaultBackend property.

CachingServices.DefaultBackend = new MemoryCachingBackend();

By default, the Default instance is used. To use other instance of the MemoryCache than the default one, an instance of the MemoryCache class can be passed to the constructor of the MemoryCachingBackend class.

MemoryCache cache = new MemoryCache( "myCache" );
CachingServices.DefaultBackend = new MemoryCachingBackend( cache );

See MSDN for details on the MemoryCache class.

In-memory caching for .NET Standard and .NET Core

To use an instance implementing the Microsoft.Extensions.Caching.Memory.IMemoryCache interface to store cached values in memory:

  1. Add a reference to the PostSharp.Patterns.Caching.IMemoryCache package.

  2. Assign an instance of a MemoryCacheBackend class to the DefaultBackend property. Pass the IMemoryCache to the constructor.

    IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());
    CachingServices.DefaultBackend = new MemoryCacheBackend(cache);
    

See Cache in-memory in ASP.NET Core on MSDN for more information on the use of IMemoryCache.