Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading assemblies at runtime and creating instances using Activator.CreateInstance()

I am trying to load an assembly at runtime, and I'm unsure as to why I can't create an instance of a type in the assembly using the static Activator.CreateInstance(). It works with Assembly.CreateInstance().

string assemblyFilename = "MyAssembly.dll";
string assemblyName = "MyAssembly";
string typeName = "MyAssembly.MyType";

FileInfo fileInfo = new FileInfo(assemblyFilename);

This works:

var assembly = Assembly.LoadFrom(assemblyFilename);
Form form = (Form)assembly.CreateInstance(typeName);

But this does NOT work:

Assembly.LoadFrom(assemblyFilename);
Form form = (Form)Activator.CreateInstance(assemblyName, typeName).Unwrap();

FileNotFoundException thrown:

Could not load file or assembly 'MyAssembly' or one of its dependencies. The system cannot find the file specified.

EDIT:

In both cases, after the Assembly.LoadFrom() call, I can see that my assembly has been loaded when I look in AppDomain.CurrentDomain.GetAssemblies().

like image 602
Dave New Avatar asked Sep 07 '12 11:09

Dave New


People also ask

What is activator CreateInstance?

CreateInstance(ActivationContext, String[]) Creates an instance of the type that is designated by the specified ActivationContext object and activated with the specified custom activation data. CreateInstance(Type) Creates an instance of the specified type using that type's parameterless constructor.

What is activator CreateInstance in net core?

The Activator. CreateInstance method creates an instance of a type defined in an assembly by invoking the constructor that best matches the specified arguments. If no arguments are specified then the constructor that takes no parameters, that is, the default constructor, is invoked.

What is the constructor to initialize a new instance of the Assembly class?

A static constructor is called automatically. It initializes the class before the first instance is created or any static members declared in that class (not its base classes) are referenced. A static constructor runs before an instance constructor.


2 Answers

You can adjust your file with his path

var path = Assembly.GetAssembly(MyType.GetType()).Location;
var thisAssembly= Assembly.LoadFrom(path);

var TypeName = "";
Type type = thisAssembly.GetType(TypeName);
object instance = Activator.CreateInstance(type);
like image 93
Aghilas Yakoub Avatar answered Sep 30 '22 11:09

Aghilas Yakoub


You have to first load the assembly into your current AppDomain:

AppDomain.CurrentDomain.Load(File.ReadAllBytes(assemblyFileName));

EDIT: Does this work?

Form form = (Form)Activator.CreateInstance(Type.GetType(typeName))
like image 21
armen.shimoon Avatar answered Sep 30 '22 10:09

armen.shimoon