Frage

When I try to import a newly created type into another assembly, Mono.Cecil is not able to resolve it. Why is this and what can I do about it?

var resolver = new DefaultAssemblyResolver();
resolver.AddSearchDirectory(...);
var readerParameters = new ReaderParameters { AssemblyResolver = resolver };
var asm1 = AssemblyDefinition.ReadAssembly("path/to/assembly1.dll", readerParameters);
var asm2 = AssemblyDefinition.ReadAssembly("path/to/assembly2.dll", readerParameters);

// add type to one assembly
var type = new TypeDefinition("Test", "TestType", TypeAttributes.Public);
asm2.MainModule.Types.Add(type);

// import type into another assembly
var typeRef = asm1.MainModule.Import(type);

var typeDef = typeRef.Resolve(); // why does this return null?

UPDATE: I found out, that there is some sort of assembly cache. Can/Should I try to invalidate it?

War es hilfreich?

Lösung

I found out that AssemblyDefinition.ReadAssembly doesn't use the cache of DefaultAssemblyResolver, so at typeRef.Resolve() the assembly is parsed again and of course the newly added type can't be found. That's why i switched to

var resolver = new DefaultAssemblyResolver();
resolver.AddSearchDirectory(...);

var asm1 = resolver.Resolve(AssemblyNameReference.Parse(...));
var asm2 = resolver.Resolve(AssemblyNameReference.Parse(...));

...

You have to use this overload of Resolve because it's the only one which uses the cache and therefore doesn't load the assembly again. I guess this is not intended.

Thank God it's Open Source.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top