dynamic type load "problem"

  • Thread starter Thread starter Dominique Vandensteen
  • Start date Start date
D

Dominique Vandensteen

I want to dynamicly load a type (typename is defined in the database).
This type is located in the exe itself or one of the dll's in the directory
with the exe file.
When creating an instance directly it works, when using reflection none of
the dll's is "scanned".
I used following code to work around this problem.
Now I just want to know if this is the/a good way to do it, or should I use
another system.





Private Shared _assemblies As System.Reflection.Assembly() = Nothing

Private Shared Function MyGetType(ByVal typeName As String) As Type
Dim result As Type = Type.GetType(typeName)
If (Not result Is Nothing) Then Return result

If (_assemblies Is Nothing) Then
Dim dir As String =
System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutableP
ath)
Dim dlls() As String = System.IO.Directory.GetFiles(dir, "*.dll")
ReDim _assemblies(dlls.Length - 1)
For i As Integer = 0 To dlls.Length - 1
_assemblies(i) = System.Reflection.Assembly.LoadFile(dlls(i))
Next i
End If

For Each asm As System.Reflection.Assembly In _assemblies
result = asm.GetType(typeName)
If (Not result Is Nothing) Then Return result
Next asm

Return Nothing
End Function
 
Dominique,

Yes, that will work, but its awfully expensive to load all assemblies when
you need a specific type. Why not use a type name which also qualifies the
assembly name instead? Then, the type loader will dynamically load the
assembly it needs.

For example, the following code will load a type named
"MyNamespace.MyCustomType" defined in MyAssembly.dll. As long as
MyAssembly.dll is located in the same folder as the calling assembly (or if
you have a config file) then the CLR loads MyAssembly.dll for you and loads
the type.

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim typeName As String = "MyNamespace.MyCustomType, MyAssembly"
Dim t As Type = MyGetType(typeName)
Dim o As Object = Activator.CreateInstance(t)
End Sub

Function MyGetType(ByVal typeName As String) As Type
Dim t As Type
t = [Type].GetType(typeName)
Return t
End Function

I hope that helps!

Keith Fink
Microsoft Developer Support
This posting is provided "AS IS" with no warranties, and confers no rights
 
Back
Top