Esempio n. 1
0
        private CSharpCompilation CreateCompilation(string compilationContent, string assemblyName)
        {
            var sourceText  = SourceText.From(compilationContent, Encoding.UTF8);
            var syntaxTree  = _csharpCompiler.CreateSyntaxTree(sourceText).WithFilePath(assemblyName);
            var compilation = _csharpCompiler
                              .CreateCompilation(assemblyName)
                              .AddSyntaxTrees(syntaxTree);

            compilation = ExpressionRewriter.Rewrite(compilation);

            var compilationContext = new RoslynCompilationContext(compilation);

            _compilationCallback(compilationContext);
            compilation = compilationContext.Compilation;
            return(compilation);
        }
        /// <inheritdoc />
        public CompilationResult Compile(RelativeFileInfo fileInfo, string compilationContent)
        {
            if (fileInfo == null)
            {
                throw new ArgumentNullException(nameof(fileInfo));
            }

            if (compilationContent == null)
            {
                throw new ArgumentNullException(nameof(compilationContent));
            }

            _logger.GeneratedCodeToAssemblyCompilationStart(fileInfo.RelativePath);

            var startTimestamp = _logger.IsEnabled(LogLevel.Debug) ? Stopwatch.GetTimestamp() : 0;

            var assemblyName = Path.GetRandomFileName();

            var sourceText = SourceText.From(compilationContent, Encoding.UTF8);
            var syntaxTree = CSharpSyntaxTree.ParseText(
                sourceText,
                path: assemblyName,
                options: _parseOptions);

            var compilation = CSharpCompilation.Create(
                assemblyName,
                options: _compilationOptions,
                syntaxTrees: new[] { syntaxTree },
                references: _applicationReferences.Value);

            compilation = Rewrite(compilation);

            var compilationContext = new RoslynCompilationContext(compilation);
            _compilationCallback(compilationContext);
            compilation = compilationContext.Compilation;

            using (var assemblyStream = new MemoryStream())
            {
                using (var pdbStream = new MemoryStream())
                {
                    var result = compilation.Emit(
                        assemblyStream,
                        pdbStream,
                        options: new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb));

                    if (!result.Success)
                    {
                        if (!compilation.References.Any() && !_applicationReferences.Value.Any())
                        {
                            // DependencyModel had no references specified and the user did not use the
                            // CompilationCallback to add extra references. It is likely that the user did not specify
                            // preserveCompilationContext in the app's project.json.
                            throw new InvalidOperationException(
                                Resources.FormatCompilation_DependencyContextIsNotSpecified(
                                    fileInfo.RelativePath,
                                    "project.json",
                                    "preserveCompilationContext"));
                        }

                        return GetCompilationFailedResult(
                            fileInfo.RelativePath,
                            compilationContent,
                            assemblyName,
                            result.Diagnostics);
                    }

                    assemblyStream.Seek(0, SeekOrigin.Begin);
                    pdbStream.Seek(0, SeekOrigin.Begin);

                    var assembly = LoadStream(assemblyStream, pdbStream);
                    var type = assembly.GetExportedTypes().FirstOrDefault(a => !a.IsNested);
                    _logger.GeneratedCodeToAssemblyCompilationEnd(fileInfo.RelativePath, startTimestamp);

                    return new CompilationResult(type);
                }
            }
        }
 private static void RoslynCompilationCallback(RoslynCompilationContext context, IServiceProvider services)
 {
     var applicationLibraryContext = services.GetRequiredService<ApplicationLibraryContext>();
     context.Compilation = context.Compilation.AddReferences(applicationLibraryContext.AdditionalMetadataReferences);
 }