在某些集成测试的准备阶段,我必须动态生成一些引用其他程序集的程序集并将它们刷新到磁盘。我猜罗斯林是这项任务的明显选择。Roslyn 编译成功完成并将发出的程序集保存到磁盘。当我使用 ILSPy 检查结果时,我发现某些程序集引用未包含在内。
虚拟类生成代码:
public static string GenerateEmptyPublicClass([NotNull] string @namespace, [NotNull] string className)
{
if (@namespace == null) throw new ArgumentNullException(nameof(@namespace));
if (className == null) throw new ArgumentNullException(nameof(className));
var classDeclaration = SyntaxFactory.ClassDeclaration(className).AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));
var namespaceDeclaration = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(@namespace)).NormalizeWhitespace();
namespaceDeclaration = namespaceDeclaration.AddMembers(classDeclaration);
return namespaceDeclaration.NormalizeWhitespace().ToFullString();
}
组装准备代码:
blic static void GenerateAssembly([NotNull] this string sourceCode, [NotNull] string assemblyFilePath,
[NotNull] params string[] referencedAssemblyPaths)
{
if (sourceCode == null) throw new ArgumentNullException(nameof(sourceCode));
if (assemblyFilePath == null) throw new ArgumentNullException(nameof(assemblyFilePath));
var assemblyFileName = Path.GetFileName(assemblyFilePath);
var outputDirectory = Path.GetDirectoryName(assemblyFilePath);
Directory.CreateDirectory(outputDirectory);
var syntaxTree = CSharpSyntaxTree.ParseText(sourceCode);
var referencedAssemblyMetadata =
referencedAssemblyPaths.Select(x => MetadataReference.CreateFromFile(x).WithProperties(new MetadataReferenceProperties()));
var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
var compilation = CSharpCompilation.Create(assemblyFileName, new[] {syntaxTree}, referencedAssemblyMetadata, compilationOptions);
拉莫斯之舞