-
Notifications
You must be signed in to change notification settings - Fork 2
Basic Usage
In order to use the library, we must add this static option on a custom Nancy Bootstrapper. The following is the minimum need configuration to use
using Nancy.RapidCache.Extensions;
using Nancy.Routing;
using Nancy.TinyIoc;
using Nancy.Bootstrapper;
namespace MyCustomWebApp
{
public class ApplicationBootrapper : DefaultNancyBootstrapper
{
protected override void ApplicationStartup
(TinyIoCContainer container, IPipelines pipelines)
{
base.ApplicationStartup(container, pipelines);
this.EnableRapidCache(container.Resolve<IRouteResolver>(),
ApplicationPipelines);
}
}
}
Be aware that Nancy allows only 1 bootstrapper per assembly and once you inherit from DefaultNancyBootstrapper it is discoverable by Nancy. For more information see here...
Once defined on the bootstrapper, we must tell RapidCache that the operation we are responding should be cached. This is done by adding the AsCacheable fluent method with a date for expiration.
namespace MyCustomWebApp
{
public class MyModule : NancyModule
{
private int _cachedSeconds = 60;
public MyModule()
{
Get("/", _ =>
{
return Response
.AsText($"This is a cached response!!")
.AsCacheable(DateTime.UtcNow.AddSeconds(_cachedTime));
});
}
}
}
The sample above caches the operation for 60 seconds. Internally, the library keeps dates on UTC format, so any date on Local time will be transformed into UTC for the sake of consistency.
Alternatively, you can add the AsCacheable method to the Response's Negotiator:
namespace MyCustomWebApp
{
public class MyModule : NancyModule
{
private int _cachedSeconds = 60;
public MyModule()
{
Get("/", _ =>
{
return
View["TestView.html"]
.AsCacheable(DateTime.UtcNow.AddSeconds(_cachedTime));
});
}
}
}
Manually adding method by method the option of caching to the responses can get cumbersome very quickly, but Nancy allows us to add an item at the beginning of the pipeline to map the responses as cacheables on the bootstrapper:
namespace MyCustomWebApp
{
public class ApplicationBootrapper : DefaultNancyBootstrapper
{
protected override void ApplicationStartup
(TinyIoCContainer container, IPipelines pipelines)
{
base.ApplicationStartup(container, pipelines);
this.EnableRapidCache(container.Resolve<IRouteResolver>(),
ApplicationPipelines);
//Add to the pipeline the cacheable fluent methosd to all responses
pipelines.AfterRequest.AddItemToStartOfPipeline(ConfigureCache);
}
private void ConfigureCache(NancyContext context)
{
if (context.Response.StatusCode == HttpStatusCode.OK &&
(context.Request.Method == "GET" ||
context.Request.Method == "HEAD" ))
{
context.Response = context.Response
.AsCacheable(DateTime.UtcNow.AddSeconds(30));
}
}
}
}
This way we can avoid verbose repetition.