CacheDependency class in .Net Core 建立缓存与文件的依赖关系

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

.Net Core 中有 CacheDependency class 吗?好像还没有实现。

我们有任何替代方案或解决方法吗?或者有没有关于实施这个 class 的未来计划?

这是.net framework支持的非常有用的功能,没有它我如何在缓存和文件之间建立依赖关系?

您应该能够使用 ChangeToken 实现类似于 CacheDependency 的功能。您将不得不使用其中一个文件提供程序来获取 IChangeToken 的实例。然后可以将此令牌用作缓存的参数。

非常基本的示例:

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);

详细解释可以在microsoft documentation for change tokens中找到。