Thursday, March 19, 2009

Plugin Concept in .Net

Here is th VB.NET translation of this excellent Article
http://www.ottoschellekens.nl/PluginConcept.htm


Imports System.Collections.Generic
Imports System.IO
Imports System.Reflection

Public Class PluginHandler

    Private Shared _Handler As PluginHandler
    Private _haPlugins = New System.Collections.Hashtable

    Public Shared Function Create() As PluginHandler
        If _Handler Is Nothing Then
            _Handler = New PluginHandler()
        End If
        Return _Handler
    End Function

    Public Function LoadPlugins() As Int16
        Dim PluginsLoaded = 0
        'Dim Path = "c:\OceanPlugins"
        Dim Path = System.Configuration.ConfigurationManager.AppSettings("RepertoirePlugins")
        Dim dir As DirectoryInfo = New DirectoryInfo(Path)
        Dim dllFiles() As FileInfo = dir.GetFiles("*.dll")
        For Each objInfo As FileInfo In dllFiles
            If LoadPlugin(objInfo.FullName) Then
                PluginsLoaded += 1
            End If
        Next
        Return PluginsLoaded
    End Function

    Public Function LoadPlugin(ByVal sFile As String) As Boolean
        Dim assPlugin As Assembly = Assembly.LoadFile(sFile)
        Dim typPluginTypes() As Type = assPlugin.GetTypes()
        Dim bReturn As Boolean = False

        For Each typPlugin In typPluginTypes
            Dim typInterface As System.Type = typPlugin.GetInterface("Ocean.IOceanPlugin")
            If typInterface IsNot Nothing And typPlugin.IsClass Then
                Dim objFactory As Object = assPlugin.CreateInstance(typPlugin.FullName)
                Dim objPlugin As Ocean.IOceanPlugin = CType(objFactory, Ocean.IOceanPlugin)
                _haPlugins.Add(objPlugin.GetShortDescription, objPlugin)                
                bReturn = True
            End If
        Next
    End Function

    Public Function getPlugins() As Hashtable
        Return _haPlugins
    End Function

End Class

No comments:

Post a Comment