Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assembly.Load .NET Core

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?

like image 894
Timothy Ghanem Avatar asked Apr 18 '19 13:04

Timothy Ghanem


People also ask

What is assembly in .NET core?

An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. Assemblies take the form of executable (.exe) or dynamic link library (. dll) files, and are the building blocks of . NET applications.

What is a .NET assembly file?

. NET defines a binary file format, assembly, that is used to fully describe and contain . NET programs. Assemblies are used for the programs themselves as well as any dependent libraries.

What is the method to load assembly given its file name and its path?

LoadFrom(String) Loads an assembly given its file name or path.


1 Answers

С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.

like image 132
Alieh S Avatar answered Oct 14 '22 04:10

Alieh S