10

I have an assembly that was dynamically generated using AssemblyBuilder.DefineDynamicAssembly, yet when i try to load it, i get the following error:

System.IO.FileNotFoundException: 'Could not load file or assembly 'test, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.'

This is the full code to reproduce:

var name = new AssemblyName("test");
var assembly = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
var assembly2 = Assembly.Load(name);

I am using .NET Core 2.0, 2.1 and 2.2.

Can somebody please explain why this happens and any possible solutions?

Timothy Ghanem
  • 1,606
  • 11
  • 20
  • 1
    [**Maybe**](https://stackoverflow.com/questions/43966687/asp-net-core-could-not-find-file-or-assembly-with-custom-assembly) of use? – Trevor Apr 18 '19 at 13:50

1 Answers1

1

Сause of error

You defined a dynamic assembly with the access mode AssemblyBuilderAccess.Run, which does not allow to save the assembly. Then, you try to load the assembly with the Load method of the Assembly class, which searches for a file.

Solution

If you want to work with a dynamic assembly in memory, you already got it. The next step is to define modules, types, and another with the help of other builders.

var moduleBuilder = assembly.DefineDynamicModule("test");
var typeBuilder = moduleBuilder.DefineType("someTypeName");
var type = typeBuilder.CreateType();
var instance = Activator.CreateInstance(type);

More information you will find in .NET API Docs.

Alieh S
  • 170
  • 2
  • 8
  • I'm not looking to save the Assembly to disk neither do i have a problem using it to create and consume types. The issue is i want to be able to get a reference to the assembly by its name just like Assembly.Load does. – Timothy Ghanem Apr 21 '19 at 11:39
  • The AssemblyBuilder class inherits from Assembly. If you need a clean Assembly class, type cast: Assembly(assemblyBuilder). – Alieh S Apr 21 '19 at 13:00
  • I do not think it is possible to simply get a link to the assembly by name. The assembly should be in some kind of global container (like a file system or a custom container in memory). And now it's just an object of the Assembly class. – Alieh S Apr 21 '19 at 13:07
  • Is there any reference to this in MSDN? – Timothy Ghanem Apr 21 '19 at 13:15
  • It depends on what we are talking about. Here is a link to [AssemblyBuilder class](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.emit.assemblybuilder?view=netcore-2.2), where the order of inheritance is specified: Object -> Assembly -> AssemblyBuilder. About the container, these are my thoughts. We have an ordinary object in memory. By default, it is bound to a variable only. Next, we ourselves need to think about where to place it in order to get the assembly by name. – Alieh S Apr 21 '19 at 13:24