在某些集成测试的准备阶段,我必须动态生成一些具有对其他程序集的引用的程序集并将其刷新到磁盘。我猜罗斯林显然是完成这项任务的选择。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);
using (var fs = File.Create(assemblyFilePath))
{
var emitResult = compilation.Emit(fs);
if (!emitResult.Success)
{
var failures = emitResult.Diagnostics.Where(x => x.IsWarningAsError || x.Severity == DiagnosticSeverity.Error);
var errorReport = failures.Select(x => $"{x.Id}: {x.GetMessage()}, {x.Location}");
throw new InvalidOperationException($"Failed to compile source code {sourceCode}. Report: {errorReport}");
}
fs.Flush();
}
}
为简单起见,我想生成两个程序集:
这里是代码:
var emptyClassSourceCode = RoslynAssemblyGenerator.GenerateEmptyPublicClass("DummyNamespace", "DummyClass");
var standardAssemblyLocation = Path.Combine(Path.GetDirectoryName(Common.ExecutingAssemblyFullPath), "Resources", "netstandard.dll");
// A references B
var aPath = Path.Combine(AssemblyGenerationPath, "A.dll");
var bPath = Path.Combine(AssemblyGenerationPath, "B.dll");
emptyClassSourceCode.GenerateAssembly(bPath, standardAssemblyLocation);
emptyClassSourceCode.GenerateAssembly(aPath, bPath, standardAssemblyLocation);
B产生了预期的,但A不引用B:
无法弄清楚我错过了什么,为什么A没有引用B。
正如在评论中提到的PetSerAl一样,为了引用程序集,我们不仅需要指示程序集位置,还需要实际使用其元数据。