FusionCache supports extensibility via plugins: it is possible for example to listen to events and react in any way you want.
In time, the most useful plugins will be listed directly in the homepage.
Simply write a class that implements the IFusionCachePlugin
interface, which basically boils down to implement just the Start
and Stop
methods: from there you can setup your custom logic and do your thing.
Of course it can also accept its own set of options, typically modelled via IOptions<MyPluginType>
and friends.
If you like there's a 🧩 complete sample available.
Register your plugin type in the DI container (better before registering FusionCache itself) to respond to the IFusionCachePlugin
service as a singleton: when a FusionCache instance will be requested, all plugin types registered will be auto-discovered, added (and started) automatically.
Of course you can also define your own custom ext method to be a better .NET citizen (see the full example below).
Example:
[...]
services.AddSingleton<IFusionCachePlugin, MyPlugin>();
services.AddFusionCache();
[...]
or with your own custom ext method + custom options:
[...]
services.AddMyFusionCachePlugin(options => {
options.Whatever = 42;
});
services.AddFusionCache();
[...]
Of course you can register multiple plugins, all responding to the same IFusionCachePlugin
service, and they will all be picked up by FusionCache when needed.
Example:
[...]
services.AddSingleton<IFusionCachePlugin, MyFirstPlugin>();
services.AddSingleton<IFusionCachePlugin, MySecondPlugin>();
services.AddFusionCache();
[...]
Just create an instance of your plugin and pass it to the cache.AddPlugin
method.
Example:
var firstPlugin = new MyFirstPlugin();
var secondPlugin = new MySecondPlugin();
var cache = new FusionCache(new FusionCacheOptions());
cache.AddPlugin(firstPlugin);
cache.AddPlugin(secondPlugin);
Start
method of your plugin throws and exception, an InvalidOperationException
would also be thrown by the AddPlugin
method itself (with the original exception as the inner one), whereas in the DI way this is already taken care of and no unhandled exception will be thrown. In both cases the original exception will be logged.
Normally there's no need to remove a plugin manually: if you just want to clean things up "at the end" (and you should do it) you don't have to do anything because when a FusionCache
instance is disposed, all added plugins will be automatically stopped and removed.
If though, for whatever reason, you need to keep using a FusionCache instance after removing a particular plugin you've previously added, you can call the cache.RemovePlugin
method: it will automatically call the Stop
method of the plugin and then remove it.
Want to follow a complete, end-to-end example to create your first plugin? There's one available 🧩 right here.