예제 #1
0
        protected virtual Type Load(RazorSourceDocument source, string relativePath)
        {
            var document = _engine.CreateCodeDocument(source);

            var parsed = RazorParser.Parse(source);

            document.SetSyntaxTree(RazorParser.Parse(source));
            foreach (var error in parsed.Diagnostics)
            {
                document.ErrorSink.OnError(error);
            }

            AddVirtualDocuments(document, relativePath);

            var @namespace = GetNamespace(relativePath);
            var @class     = "Generated_" + Path.GetFileNameWithoutExtension(Path.GetFileName(relativePath));

            document.WithClassName(@namespace, @class);

            _engine.Process(document);
            if (document.ErrorSink.Errors.Any())
            {
                throw CreateException(document);
            }

            var compilation = CreateCompilation(@class, @namespace, relativePath, document.GetGeneratedCSharpDocument().GeneratedCode);
            var text        = compilation.SyntaxTrees[0].ToString();

            using (var pe = new MemoryStream())
            {
                using (var pdb = new MemoryStream())
                {
                    var emitResult = compilation.Emit(
                        peStream: pe,
                        pdbStream: pdb,
                        options: new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb));
                    if (!emitResult.Success)
                    {
                        throw CreateException(document, relativePath, text, compilation.AssemblyName, emitResult.Diagnostics);
                    }

                    pe.Seek(0, SeekOrigin.Begin);
                    pdb.Seek(0, SeekOrigin.Begin);

                    var assembly = LoadStream(pe, pdb);
                    var type     = assembly.GetExportedTypes().FirstOrDefault(a => !a.IsNested);
                    return(type);
                }
            }
        }