Automating FusionCache with a Source Generator: A Step-by-Step Guide

Automating FusionCache with a Source Generator: A Step-by-Step Guide Using a source generator to automate code for calling the GetOrSetAsync function from FusionCache is an elegant way to handle caching. Let’s walk through how you can use Roslyn, the .NET Compiler Platform, to create a generator tailored to your needs. Step 1: Create the Custom Attribute Start by defining a FusionCacheAttribute that will decorate the methods you want to cache: ...

March 15, 2025 · 2 min · Taner

Mastering Aspect-Oriented Programming (AOP): Concepts and Examples

To create a code generator that automatically caches any function with a cache attribute that takes a duration, you can use a source generator in .NET. Source generators allow you to generate additional source code at compile time. Step 1: Define the Cache Attribute First, define the cache attribute that will be used to mark methods for caching: using System; [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] public sealed class CacheAttribute : Attribute { public CacheAttribute(int durationInSeconds) { DurationInSeconds = durationInSeconds; } public int DurationInSeconds { get; } } Step 2: Create the Source Generator Next, create the source generator that will generate the caching logic for methods marked with the CacheAttribute. ...

March 15, 2025 · 3 min · Taner