Skip to content

SpatialFocus/MethodCache.Fody

Repository files navigation

SpatialFocus.MethodCache.Fody

A method cache Fody plugin

Nuget Build & Publish FOSSA Status

Caches return values of methods decorated with a [Cache] Attribute. Integrates with the .NET Extension IMemoryCache interface.

Usage

See also Fody usage.

NuGet installation

Install the SpatialFocus.MethodCache.Fody NuGet package and update the Fody NuGet package:

PM> Install-Package Fody
PM> Install-Package SpatialFocus.MethodCache.Fody

The Install-Package Fody is required since NuGet always defaults to the oldest, and most buggy, version of any dependency.

Add to FodyWeavers.xml

Add <SpatialFocus.MethodCache/> to FodyWeavers.xml

<Weavers>
    <SpatialFocus.MethodCache/>
</Weavers>

Overview

Before code:

[Cache]
public class BasicSample
{
    public BasicSample(IMemoryCache memoryCache)
    {
        MemoryCache = memoryCache;
    }

    // MethodCache.Fody will look for a property implementing
    // the Microsoft.Extensions.Caching.Memory.IMemoryCache interface
    protected IMemoryCache MemoryCache { get; }

    public int Add(int a, int b)
    {
        return a + b;
    }
}

What gets compiled

[Cache]
public class BasicSample
{
    public BasicSample(IMemoryCache memoryCache)
    {
        MemoryCache = memoryCache;
    }

    protected IMemoryCache MemoryCache { get; }

    public int Add(int a, int b)
    {
        // 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 parameters
        Tuple<string, int, int> key = new Tuple<string, int, int>("Namespace.BasicSample.Add", a, b);

        // Check and return if a cached value exists for key
        if (MemoryCache.TryGetValue(key, out int value))
        {
            return value;
        }

        // Before each return statement, save the value that would be returned in the cache
        value = a + b;
        MemoryCache.Set<int>(key, value);
        return value;
    }
}

License

FOSSA Status


Made with ❤️ by Spatial Focus