During the preparation stage of some integration testing, I have to dynamically generate some assemblies with references to other assemblies and flush them to disk. The obvious choice for this task is Roslyn I guess. Roslyn compilation completes successfully and emitted assemblies saved to disk. When I check the result using ILSPy, I see that some assembly references are not included.
Dummy class generation code:
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();
}
Assembly preparation code:
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();
}
}
For simplicity, I want to generate two assemblies:
Here goes the code:
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 is generated as expected, but A does not refer to B:
Can't figure out what have I missed, why B is not referenced by A.
As PetSerAl mentioned in the comment, in order to reference assembly we need not only indicate assembly location but actually use its metadata.