Question about reflection

  • Thread starter Thread starter Andre Nogueira
  • Start date Start date
A

Andre Nogueira

Hi guys

I am developing a plugin-enabled application, and for that I am using
reflection.
I created an abstract ("MustInherit") class, from which all plugins must
inherit.
My question is... How do I make sure the .dll the users select are actually
plugins? I'm currently enforcing a policy where the concrete plugins need to
have a certain string somewhere in the classe's name, but that is not at all
a good idea...
What do you guys propose? What is the best way to ensure that this is
actually a plugin with the functions my applications expects the plugins to
have?

If it helps, I'm developing this in VB.Net using .Net 2.0.

Thanks in advance!

André Nogueira
 
Hello, Andre!

If the assemly has the type ( interface ) your application is expecting then it is the plugin your app supports, if there is no such type in the assembly then it is not plugin.

--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com
 
Hi,

Thanks for the reply! I'm now using this code:

For Each t As Type In Plugin.GetTypes

If t.ToString.Contains("<my base plugin's base class>") Then

IsPlugin = True

End If

Next

It's not perfect (people can create a class which has the same class name,
and it would be identified as a plugin, but it's acceptable, I guess.

One more question though...

I have this code to load the plugin:

Dim Plugin As System.Reflection.Assembly = Nothing

Plugin = Reflection.Assembly.LoadFrom(FileName)

Dim typeObj As Type = Plugin.GetType(TypeName, True, True)

Dim instance As Object = Activator.CreateInstance(typeObj)

But... How do I know what the string "TypeName" should hold? Right now I'm
using a fixed name in the test plugins I'm creating, but people should be
able to name their classes anything they want... Is there any way to
overcome this, and still load the plugin - now knowing in advance what the
class name is?

Thanks again!

Andre Nogueira
 
Hi Vadym

use the the overlaoded method of create instance which deal with types:


Dim Plugin As System.Reflection.Assembly = Nothing
Plugin = Reflection.Assembly.LoadFrom(FileName)
Dim typeObj As Type = Plugin.GetType(TypeName, True, True)
Dim instance As Object =
Activator.CreateInstance(GetType(<YourInterface>))

Regards,

Marcus
 
Andre said:
For Each t As Type In Plugin.GetTypes

You really should use Assembly.GetExportedTypes, not
Assembly.GetTypes. GetTypes returns all types - including private and
internal types that you can't access (without special permissions) -
while GetExportedTypes only returns public types. Smaller array, and
no special permissions required.
If t.ToString.Contains("<my base plugin's base class>") Then

Yuck! You really want to use Type.IsAssignableFrom, not string tests!

typeof(MyAbstractBaseClass).IsAssignableFrom(t)

(though it's probably better to use an interface than an abstract base
class.)
 
Back
Top