System.Reflection.Assembly.LoadFrom + passing variables

  • Thread starter Thread starter binder.christian
  • Start date Start date
B

binder.christian

Hi!

I have two applications:
* mainapp.exe
* plugin01.exe

I have 2 "friend" variables in mainapp.exe:
Friend gblConn as SqlConnection
Friend gblPath as string

When mainapp.exe starts, gblConn is declared as a new SqlConnection
and connects to the database, gblPath is filled with the current
application path.

If the user clicks "Button1" in Form1 of mainapp.exe, "PluginForm" of
plugin01.exe is loaded by this code:
Dim extAssembly As System.Reflection.Assembly =
System.Reflection.Assembly.LoadFrom("c:\plugin01.exe")
Dim extform As Form =
extAssembly.CreateInstance("plugin01.PluginForm", True)
Form1.AddOwnedForm(extform)
extform.Show()

Everything works fine so far.

The problem is that I want to share the 2 friend-variables in
mainapp.exe with plugin01.exe (so I can use the same connection -
gblConn - for both applications, etc.).

So, how can I pass / share the variables from mainapp.exe to
plugin01.exe?
 
Hi,

What you need is to create a method in the PluginForm that will accept
glbConn and glbPath as parameters and store them in PluginForm's private
fields:

Public Sub SetParams(conn as SqlConnection, path as String)
prvConn = conn
prvPath = path
End Sub

Then what's left is to call that method and pass glbConn and glbPath as its
parameters.

There are 2 ways to do that:

1. Use Reflection

Since you do not know the exact type of PluginForm in mainapp, you have
to assume the method SetParams is there and invoke it by name:

Dim t As Type = extform.GetType()

Dim p As Object() = { gblConn , gblPath }
t.GetMethod("SetParams").Invoke(extform, p)

2. Use an interface

You could also declare an interface in another module, e.g. Common,
which you would reference in mainapp and in plugin01:

Public Interface IPlugin
Sub SetParams(ByRef conn As SqlConnection, ByVal path As String)
End Interface

Then you should make PluginForm implement that interface.

In mainapp, you can then cast the result of CreateInstance to that
interface:
Dim extform As IPlugin = extAssembly.CreateInstance("plugin01.PluginForm",
True)

and call the SetParams method thru that interface:
extform.SetParams(gblConn, gblPath)



Hope this helps,

_____________
Adam Bieganski
http://godevelop.blogspot.com
 
Hi!

Both methods work great! Thank you very much! :-)

With kind regards

Christian Binder
 
Back
Top