嵌入式剃须刀视图

时间:2011-07-07 18:50:06

标签: asp.net-mvc razor

最近,我读了一篇post,其中作者描述了我们如何将剃刀视图编译成单独的库。我想问一下,是否可以在没有编译的情况下在库中嵌入视图?然后,添加自定义VirtualPathProvider以读取视图。

2 个答案:

答案 0 :(得分:2)

您可以使用可以通过Nuget安装的EmbeddedResourceVirtualPathProvider。它从引用的程序集中加载资源,也可以设置为在开发期间依赖源文件,这样您就可以更新视图而无需重新编译。

答案 1 :(得分:1)

在你的“shell”MVC项目的Global.asax Application_Start中注册你的自定义VirtualPathProvider:

HostingEnvironment.RegisterVirtualPathProvider(new CustomVirtualPathProvider());

实际的实现会比这更复杂,因为你可能会做一些基于接口的,反射,数据库查找等作为拉动元数据的方法,但这是一般的想法(假设你有另一个命名的MVC项目带有Foo控制器和Index.cshtml视图的“AnotherMvcAssembly”被标记为嵌入式资源:

public class CustomVirtualPathProvider : VirtualPathProvider {
    public override bool DirectoryExists(string virtualDir) {
        return base.DirectoryExists(virtualDir);
    }

    public override bool FileExists(string virtualPath) {
        if (virtualPath == "/Views/Foo/Index.cshtml") {
            return true;
        }
        else {
            return base.FileExists(virtualPath);
        }
    }

    public override System.Web.Caching.CacheDependency GetCacheDependency(string virtualPath, System.Collections.IEnumerable virtualPathDependencies, DateTime utcStart) {
        if (virtualPath == "/Views/Foo/Index.cshtml") {
            Assembly asm = Assembly.Load("AnotherMvcAssembly");
            return new CacheDependency(asm.Location);
        }
        else {
            return base.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
        }
    }

    public override string GetCacheKey(string virtualPath) {
        return base.GetCacheKey(virtualPath);
    }

    public override VirtualDirectory GetDirectory(string virtualDir) {
        return base.GetDirectory(virtualDir);
    }

    public override VirtualFile GetFile(string virtualPath) {
        if (virtualPath == "/Views/Foo/Index.cshtml") {
            return new CustomVirtualFile(virtualPath);
        }
        else {
            return base.GetFile(virtualPath);
        }
    }
}

public class CustomVirtualFile : VirtualFile {
    public CustomVirtualFile(string virtualPath) : base(virtualPath) { }

    public override System.IO.Stream Open() {
        Assembly asm = Assembly.Load("AnotherMvcAssembly");
        return asm.GetManifestResourceStream("AnotherMvcAssembly.Views.Foo.Index.cshtml");
    }
}