tags:

views:

22

answers:

1

Hello,

I'm using the following code in a vb.net 2008 project to dynamically load dll's (with forms) from a folder, all works great however I can't figure out for the life of me how to call a function or get a public variable from the plugins.

Can anyone answer this issue for me?

Dim PluginList As String() = Directory.GetFiles(appDir, "*.dll")

For Each Plugin As String In PluginList

    Dim Asm As Assembly
    Dim SysTypes As System.Type
    Asm = Assembly.LoadFrom(Plugin)
    SysTypes = Asm.GetType(Asm.GetName.Name + ".frmMain")
    Dim IsForm As Boolean = GetType(Form).IsAssignableFrom(SysTypes)
    If IsForm Then
            Dim tmpForm As Form = CType(Activator.CreateInstance(SysTypes), Form)
+1  A: 

You should probably create an interface in a common assembly and have your form implement it, this way you can cast you dynamically loaded object as your interface type.

Imports System.Reflection
Imports Plugin.Interfaces

Sub Main()
    Dim assembly As Assembly
    assembly = assembly.LoadFrom("Plugin.X.dll")

    Dim type As Type
    Dim found As Boolean = False

    For Each type In assembly.GetTypes()
        If GetType(IForm).IsAssignableFrom(type) Then
            found = True
            Exit For
        End If
    Next

    If found Then
        Dim instance As IForm
        instance = CType(Activator.CreateInstance(type), IForm)

        Console.WriteLine(instance.Add(20, 20))
    End If
End Sub

Interface Assembly

Public Interface IForm
    Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
End Interface

Plugin Assembly

Imports Plugin.Interfaces

Public Class Form
    Implements IForm

    Public Function Add(ByVal x As Integer, ByVal y As Integer) As Integer Implements IForm.Add
        Return x + y
    End Function

End Class
Rohan West
That set me on the right path, thanks!
Joe