Skip to content

antoinebidault/DonutOutputCachingCore

Repository files navigation

ASP.NET Core donut output caching middleware

Build status NuGet

Donut server-side caching middleware for ASP.NET Core 2.0. With this package, you'll be able to pull outside the outputCache any component. The child components would be executed on each request. This is particulary useful when you have personnalized content like user profile's top nav, behavioral based contents... This library is based on the great MadKristensen's WebEssentials.AspNetCore.OutputCaching library : https://github.com/madskristensen/WebEssentials.AspNetCore.OutputCaching. Thanks to him !

The concept

DonutOutputCaching

Register the middleware

Start by registering the service it in Startup.cs like so:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddDonutOutputCaching();
}

...and then register the middleware just before the call to app.UseMvc(...) like so:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseDonutOutputCaching();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

Usage examples

There are various ways to use and customize the output caching. Here are some examples.

Component invocation

Use the classic Component.InvokeAsync attribute in a view. The boolean param excludeFromCache will specify that this component must be refreshed on each page view.

@await Component.InvokeAsync("MyComponent", excludeFromCache: true)

Action filter

Use the OutputCache attribute on a controller action:

[DonutOutputCache(Duration = 600, VaryByParam = "id")]
public IActionResult Product()
{
    return View();
}

Caching profiles

Set up cache profiles to reuse the same settings.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddDonutOutputCaching(options =>
    {
        options.Profiles["default"] = new OutputCacheProfile
        {
            Duration = 600
        };
    });
}

Then use the profile from an action filter:

[DonutOutputCache(Profile = "default")]
public IActionResult Index()
{
    return View();
}

Distributed cache option

You can use the distributed cache service instead of the standard MemoryCache

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
		services.AddSingleton<IDistributedCache, RedisDistributedCache>();
    services.AddDonutOutputCaching(options =>
    {
        options.UseDistributedCache = true;
    });
}

About

Donut output caching for ASP.NET Core

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •  

Languages