Dynamically Load Assembly (Windows Service)

  • Thread starter Thread starter dercon
  • Start date Start date
D

dercon

I'm attempting to dynamically load an assembly from a windows service.
However, i'm having problems when the service runs... he is the line of
code that causes the error:

dim loAssembly as Assembly = Assembly.LoadFrom("SomeDLL.dll")

I have a test windows Form that i use when developing services... this
way i can run the service in debug mode. If i run as a windows form,
the code executes fine and the assembly loads. However, when i compile
and run as a windows service, the above line of code does not execute.

I'm guessing that while a windows service, the app is running in a
different context -- but i'm not sure. Any help would be appreciated.

Thanks!
 
dercon said:
and run as a windows service, the above line of code does not
execute.

What does this mean? Are you getting an exception? Can you post any
exceptions generated?

A little more information is needed.

Does your service run under an account that has sufficient priveleges
to load the assembly?
 
I fixed the initial issue... turns out that since the application is
running as a service, its base directory is the /windows/system32
directory so it was not finding the dll. I simply passed in the full
path to the dll and i was able to load the assembly.

However, a new issue has surfaced... i can load the assembly but i
can't create a class from the dll...

dim moDLL as SomeNamespace.SomeClass
loAssembly = Assembly.LoadFrom("C:\sswork\MyDLL.dll)
'The following line fails to create.
moDLL = loAssembly.CreateInstance("SomeNamespace.SomeClass")

I'm getting the following error when i attempt to create my class
instance:
System.InvalidCastException: Specified cast is not valid.

However, if i start the service and attach it to the development
environment, if i manually create instance (using the command window)
the code works fine.

Any ideas?
 
Off the top of my head, it appears you are not casting the result of
the CreateInstance call to your class type. CreateInstance returns
Object so you would have to cast the object to your class:

moDLL = DirectCast(loAssembly.CreateInstance("SomeClass"),SomeClass)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top