1

I need to create an instance of a class, while only having the full class name (with namespaces) and the file-name of the assembly where the class is defined. I know that the assembly is in the current working directory. The default constructor (with no arguments) should be used, as it is the only one available.

After some google, stack overflow and MSDN I am still not sure what the best solution is. Multiple assemblies will be loaded, so using an application domain would be good (?).

The application domain documentation says, I should use CreateInstanceAndUnwrap, but there I need the full assembly name. And as far as I know, I only can get it by loading the assembly. This seems somewhat very inefficient.

Which is a good way to create an instance of a class in a currently unloaded assembly?

Thanks!

Kenney
  • 9,003
  • 15
  • 21
Leifb
  • 370
  • 7
  • 20

2 Answers2

2

If the assembly is already in the bin folder or GAC, you don't have to load the assembly manually.

You can simply use Activator.CreateInstance to instantiate the object.

The string you pass in to CreateInstance must be the assembly qualified type name, meaning, type-name followed by a comma and the assembly name. For example MyNameSpace.MyObject, MyAssembly.

This should always work.

MichaC
  • 13,104
  • 2
  • 44
  • 56
  • Oh, that actually works! I thought that you need to load the assembly if its not used elsewhere in your program. Thanks! – Leifb Feb 22 '16 at 17:06
1

I believe you want Assembly.LoadFrom. This gives you the assembly by filename, which can then be used to instantiate the class through reflection.

Ultimately, you need to load the assembly, since it contains the code necessary to define and instantiate the class. You are on the right track by using an AppDomain, however, as this will let you later unload the assembly.

Squimmy
  • 567
  • 3
  • 5