lundi 4 juillet 2016

How to convert a type, loaded from one project, to an interface

Prerequisites

  • .NET environment
  • A Common assembly with an interface IModule
  • Main project, referencing Common
  • Implementor project, referencing Common, but not referenced from Main When everything is built, the Common.dll is present in both Main and Implementor.

Now the Main project tries to load the class implementing IModule at runtime. What I could achieve so far:

Dim asm = Assembly.LoadFrom(asmFile)
For Each asmType in asm.GetExportedTypes()
    If asmType.IsClass AndAlso
       asmType.GetInterfaces().Any(Function(i) i.Name = GetType(IModule).Name) Then
        Dim handle = AppDomain.CurrentDomain.CreateInstanceFrom(asmFile, asmType.FullName)
        Dim inst = CType(handle.Unwrap(), IModule) ' EXCEPTION
    End If
Next

So I can load the Implementor assembly and find the type implementing IModule. But I can't create an instance of it such that I can cast it to my local IModule. Is this at all possible?

Workaround

I found a workaround - in Implementor project, click on reference to Common and clear "Copy Local" flag. Then I can even use simpler code, like IsAssignableFrom(). But is this the only way? What if I get a DLL from third party, where the IModule is compiled into it?





Aucun commentaire:

Enregistrer un commentaire