【问题标题】:Prevent view caching in Nancy when using the Spark template engine使用 Spark 模板引擎时防止 Nancy 中的视图缓存
【发布时间】:2014-04-16 00:14:01
【问题描述】:

我正在使用带有 Spark 模板的自托管 Nancy。我已经专门禁用了缓存(尽管在 DEBUG 中应该默认禁用)。

    protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, IPipelines pipelines)
    {
        base.ApplicationStartup(container, pipelines);

        ...

        StaticConfiguration.Caching.EnableRuntimeViewDiscovery = true;
        StaticConfiguration.Caching.EnableRuntimeViewUpdates = true;
    }

但是,在应用程序运行时对模板进行更改似乎不起作用,因为模板更改没有被拾取。

禁用视图缓存还需要其他什么吗?

【问题讨论】:

    标签: c# nancy spark-view-engine


    【解决方案1】:

    由于您的应用程序是自托管的,我猜您要么覆盖视图位置约定以在程序集中将视图作为嵌入式资源查找,要么已将 Visual Studio 项目配置为在编译时将视图复制到输出目录中时间。在这两种情况下,您的应用程序都不是在 Visial Studio 项目中的视图文件上运行,而是在它们的副本上运行。在这种情况下,缓存不是问题。

    【讨论】:

    • 实际上,我在DEBUG 中添加了一个自定义IRootPathProvider 以指向VS 项目。这可行,视图是从 VS 项目提供的,但它似乎在第一次请求后被缓存。之后对视图所做的任何更改甚至完全删除都不会被拾取。忘了提我正在使用来自 NuGet 的v0.22.2.0
    【解决方案2】:

    好的,通过在引导程序中添加自定义 ViewCache 来使其正常工作:

    public class MyBootstrapper : DefaultNancyBootstrapper
    {
    #if DEBUG
        protected override IRootPathProvider RootPathProvider
        {
            get
            {
                // this sets the root folder to the VS project directory
                // so that any template updates in VS will be picked up
                return new MyPathProvider();
            }
        }
    
        protected override NancyInternalConfiguration InternalConfiguration
        {
            get
            {
                return NancyInternalConfiguration.WithOverrides(
                    x =>
                        { x.ViewCache = typeof(MyViewCache); });
            }
        }
    #endif
    

    新的ViewCache 只是在每次请求时重新加载模板:

    public class MyViewCache : IViewCache
    {
    ...
        public TCompiledView GetOrAdd<TCompiledView>(
            ViewLocationResult viewLocationResult, Func<ViewLocationResult, TCompiledView> valueFactory)
        {
            //if (viewLocationResult.IsStale())
            //    {
                    object old;
                    this.cache.TryRemove(viewLocationResult, out old);
            //    }
    
            return (TCompiledView)this.cache.GetOrAdd(viewLocationResult, x => valueFactory(x));
        }
    }
    

    不知何故,viewLocationResult.IsStale() 总是返回 false

    默认情况下,这是FileSystemViewLocationResult 的一个实例,它只是比较视图的最后更新时间,但时间戳this.lastUpdated 在从DefaultViewCache 调用IsStale() 之前已被更新,因此模板永远不会从缓存中删除

    public override bool IsStale()
    {
        return this.lastUpdated != this.fileSystem.GetLastModified(this.fileName);
    }
    

    【讨论】:

    • 看起来不错,但不完整。你如何覆盖 FileSystemViewLocationResult?
    猜你喜欢
    • 2012-03-20
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    • 2014-10-18
    相关资源
    最近更新 更多