A method cache Fody plugin
Caches return values of methods decorated with a [Cache] Attribute. Integrates with the .NET Extension IMemoryCache interface.
See also Fody usage.
Install the SpatialFocus.MethodCache.Fody NuGet package and update the Fody NuGet package:
PM>Install-Package Fody
PM>Install-Package SpatialFocus.MethodCache.FodyThe Install-Package Fody is required since NuGet always defaults to the oldest, and most buggy, version of any dependency.
Add <SpatialFocus.MethodCache/> to FodyWeavers.xml
<Weavers>
<SpatialFocus.MethodCache/>
</Weavers>Before code:
[Cache]publicclassBasicSample{publicBasicSample(IMemoryCachememoryCache){MemoryCache=memoryCache;}// MethodCache.Fody will look for a property implementing// the Microsoft.Extensions.Caching.Memory.IMemoryCache interfaceprotectedIMemoryCacheMemoryCache{get;}publicintAdd(inta,intb){returna+b;}}What gets compiled
[Cache]publicclassBasicSample{publicBasicSample(IMemoryCachememoryCache){MemoryCache=memoryCache;}protectedIMemoryCacheMemoryCache{get;}publicintAdd(inta,intb){// Create a unique cache key, based on namespace, class name and method name as first parameter// and corresponding generic class parameters, generic method parameters and method parametersTuple<string,int,int>key=newTuple<string,int,int>("Namespace.BasicSample.Add",a,b);// Check and return if a cached value exists for keyif(MemoryCache.TryGetValue(key,outintvalue)){returnvalue;}// Before each return statement, save the value that would be returned in the cachevalue=a+b;MemoryCache.Set<int>(key,value);returnvalue;}}Made with ❤️ by Spatial Focus