Search code examples
c#dll.net-assembly

C# create instance of type from DLL extending host application type


Is this possible if not could some one please explain how i could implement this to work?

So i have a C# Application and a folder with it called modules, so files:

Application.exe
modules/
        Application.Handler.ModuleName.dll

So inside the DLL it has the namespace Application.Handle containing the type ModuleName and ModuleName extends Handler that is implemented in Application.exe so to compile requires Application.exe as a reference.

Inside my host application i have:

 string[] dirs = Directory.GetFiles(@"modules/", "Application.Handler.*.dll");
 foreach(string filePath in dirs)
 {
      Assembly.LoadFile(new FileInfo(filePath).FullName);

      string fileName = filePath.Split('/').Last();
      string typeAssemblyName = fileName.Replace(".dll", "");
      string typeName = typeAssemblyName.Split('.').Last();
 }

But i'm unsure if i can implement the types from the strings i thought i could with Activator.CreateInstance but i'm not sure if I'm doing it correctly or if the way I'm trying to implement it works?

UPDATE I might not have been clear but effectively what i need to do is Application.Handler handler = new Application.Handler.ModuleName() Where Application.Handler.ModuleName in php it's done like below i thought there would be a system that returns an object of the type given in the string. if it's not there throw an exception

$className = "\Application\Handler\ModuleName"; 
$instance = new $className();

I have also tried using the Unwrap system that @rene suggested

Assembly asm = Assembly.LoadFile(new FileInfo(filePath).FullName);

string fileName = filePath.Split('/').Last();
string typeAssemblyName = fileName.Replace(".dll", "");
string typeName = typeAssemblyName.Split('.').Last();
FrameHandler fh;
fh = (FrameHandler)Activator.CreateInstance(asm.FullName, typeAssemblyName).Unwrap();
fh.RegisterHandlers();

using this method where i give it the Assembly name it gives me a FileNotFoundException and without the Assembly name i get TypeLoadException but it must be loading the manifest of the assembly as Application.Handler.ModuleName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null


Solution

  • You just need a handle to the type, so you'll need the assembly path and the type's full name.

    var assy = Assembly.LoadFile("...");
    var type = assy.GetType("...");
    var obj = Activator.CreateInstance(type);