Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CacheDependency class in .Net Core to establishes a dependency relationship between cache and file

Is there CacheDependency class in in .Net Core? Seems like that's not implemented yet.

Do we have any alternate or workaround for that? Or is there any future plan about implementation of this class?

This is very useful functionality which was supported in .net framework, how can I establishes a dependency relationship between cache and file without it ?

like image 446
Jay Shah Avatar asked Jan 02 '23 18:01

Jay Shah


1 Answers

You should be able to use ChangeToken to achieve functionality similar to CacheDependency. You will have to use one of file providers to get instance of IChangeToken. This token can then be used as parameter for cache.

Very basic sample:

IMemoryCache cache = GetCache();
string fileContent = GetFileContent("sample.txt");

// instance of file provider should be ideally taken from IOC container
var fileProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory()); 

IChangeToken token = _fileProvider.Watch("sample.txt");

// file will be removed from cache only if it is changed
var cacheEntryOptions = new MemoryCacheEntryOptions()
            .AddExpirationToken(changeToken);

// put file content into cache 
cache.Set("sample.txt", fileContent, cacheEntryOptions);

Detailed explanation can be found in microsoft documentation for change tokens.

like image 125
Marian Polacek Avatar answered Feb 27 '23 08:02

Marian Polacek