StoneCodeMonkey
Well-known member
- Joined
- Apr 17, 2009
- Messages
- 56
- Programming Experience
- 5-10
Hello,
I would like to load a class library at runtime. As such, I thought I could use reflection to do so. However I am receiving the exception "Unable to cast object of type 'MyLibrary.LogSystem' to type 'MainApp.ILog'." in my main application. To start with I created a Class Library (VS2010) with a simple interface and one class that implements the interface.
Then I created a Winform application and added the exact same interface. In the load event for the form I used reflection to load the assembly file.
Everthing works up to the point where I try to create an instance:
log = CType(PlugInAssembly.CreateInstance(PlugInType.FullName), MainApp.ILog)
This is where I get the error. Any ideas?
Regards,
I would like to load a class library at runtime. As such, I thought I could use reflection to do so. However I am receiving the exception "Unable to cast object of type 'MyLibrary.LogSystem' to type 'MainApp.ILog'." in my main application. To start with I created a Class Library (VS2010) with a simple interface and one class that implements the interface.
VB.NET:
Public Interface ILog
Sub Write(ByVal filePath As String, ByVal Fields() As String, ByVal Values() As String)
End Interface
VB.NET:
Public Class LogSystem
Implements ILog
Public Sub Write(ByVal filePath As String, ByVal Fields() As String, ByVal Values() As String) Implements ILog.Write
MsgBox("Written")
End Sub
End Class
Then I created a Winform application and added the exact same interface. In the load event for the form I used reflection to load the assembly file.
VB.NET:
Public Class formMain
Private log As MainApp.ILog
Private Sub formMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim assyPath As String = "C:\My\Visual Studio\Visual Basic\Personal\Runtime Reference\Booya\Booya\bin\Release\MyLibrary.dll"
Try
Dim PlugInAssembly As Reflection.Assembly = Reflection.Assembly.LoadFrom(assyPath)
Dim Types() As Type
Dim FoundInterface As Type
Types = PlugInAssembly.GetTypes
For Each PlugInType As Type In Types
FoundInterface = PlugInType.GetInterface("MyLibrary.ILog")
If FoundInterface IsNot Nothing Then
log = CType(PlugInAssembly.CreateInstance(PlugInType.FullName), MainApp.ILog)
Exit For
End If
Next
Catch ex As Exception
Debug.Print(ex.Message)
End Try
End Sub
End Class
Everthing works up to the point where I try to create an instance:
log = CType(PlugInAssembly.CreateInstance(PlugInType.FullName), MainApp.ILog)
This is where I get the error. Any ideas?
Regards,