public IRazorPage CreateInstance([NotNull] string relativePath, Stream stream) { if (relativePath.StartsWith("~/", StringComparison.Ordinal)) { // For tilde slash paths, drop the leading ~ to make it work with the underlying IFileProvider. relativePath = relativePath.Substring(1); } // Code below is taken from CompilerCache (specifically OnCacheMiss) which is responsible for managing the compilation step in MVC // Check the file var fileProvider = stream == null ? (IFileProvider)_fileProvider : new WyamStreamFileProvider(_fileProvider, stream); var fileInfo = fileProvider.GetFileInfo(relativePath); if (!fileInfo.Exists) { return(null); } // If relative path is the root, it probably means this isn't from reading a file so don't bother with caching IExecutionCache cache = relativePath == "/" ? null : _executionContext.ExecutionCache; string key = null; Type pageType = null; if (cache != null) { key = relativePath + " " + RazorFileHash.GetHash(fileInfo); if (!cache.TryGetValue(key, out pageType)) { pageType = null; } } // Compile and store in cache if not found if (pageType == null) { var relativeFileInfo = new RelativeFileInfo(fileInfo, relativePath); pageType = _razorcompilationService.Compile(relativeFileInfo); cache?.Set(key, pageType); } // Create an return a new page instance IRazorPage page = (IRazorPage)Activator.CreateInstance(pageType); page.Path = relativePath; return(page); }
public ViewCollection() { var fileInfos = new List <RazorFileInfo>(); FileInfos = fileInfos; var content = new PreCompile().Content; var length = Encoding.UTF8.GetByteCount(content); fileInfos.Add(new RazorFileInfo() { FullTypeName = typeof(PreCompile).FullName, Hash = RazorFileHash.GetHash(GetMemoryStream(content)), LastModified = DateTime.FromFileTimeUtc(10000), Length = length, RelativePath = "ab", }); }
protected virtual PrecompilationCacheEntry GetCacheEntry([NotNull] RelativeFileInfo fileInfo) { using (var stream = fileInfo.FileInfo.CreateReadStream()) { var host = GetRazorHost(); var results = host.GenerateCode(fileInfo.RelativePath, stream); if (results.Success) { var syntaxTree = SyntaxTreeGenerator.Generate(results.GeneratedCode, fileInfo.FileInfo.PhysicalPath, CompilationSettings); var fullTypeName = results.GetMainClassName(host, syntaxTree); if (fullTypeName != null) { var hashAlgorithmVersion = RazorFileHash.HashAlgorithmVersion1; var hash = RazorFileHash.GetHash(fileInfo.FileInfo, hashAlgorithmVersion); var razorFileInfo = new RazorFileInfo { RelativePath = fileInfo.RelativePath, LastModified = fileInfo.FileInfo.LastModified, Length = fileInfo.FileInfo.Length, FullTypeName = fullTypeName, Hash = hash, HashAlgorithmVersion = hashAlgorithmVersion }; return(new PrecompilationCacheEntry(razorFileInfo, syntaxTree)); } } else { var diagnostics = results.ParserErrors .Select(error => error.ToDiagnostics(fileInfo.FileInfo.PhysicalPath)) .ToList(); return(new PrecompilationCacheEntry(diagnostics)); } } return(null); }