SaturnFramework / Saturn

Opinionated, web development framework for F# which implements the server-side, functional MVC pattern
https://saturnframework.org
MIT License
714 stars 108 forks source link

How to use MemoryCache? #177

Closed markpattison closed 5 years ago

markpattison commented 5 years ago

I can see a reference in the docs to an in-memory cache - is this the same as this one?

If so, I'm struggling to see how to get a reference to it in Saturn. Is there an example anywhere which shows it being used?

Many thanks!

jeremyabbott commented 5 years ago

@markpattison it actually uses the Distributed Memory Cache.

If you want to use the MemoryCache you referenced, you can wire it up like this:

service_config (fun s -> s.AddMemoryCache())

markpattison commented 5 years ago

Thank you - unfortunately I'm also struggling to see how to then get a reference to the cache, i.e. the equivalent of the following C# from the docs:

public class HomeController : Controller
{
    private IMemoryCache _cache;

    public HomeController(IMemoryCache memoryCache)
    {
        _cache = memoryCache;
    }
}
jeremyabbott commented 5 years ago

You can get access to the services via the HttpContext.

If you have a controller action like this:

let indexAction =
        fun (ctx: HttpContext) ->
            task {
                let cache = ctx.GetService<IMemoryCache>()
                let cachedValue = cache.Get("foo") :?> string // or whatever type it is
                return ok ctx cachedValue
            }

    let controller = controller {
        index indexAction
    }

GetService<'t> is an extension on HttpContext that's added by Giraffe so you'll need to open Giraffe before it's available to you.

markpattison commented 5 years ago

Got it working, thanks again for the help!