executing code upon assembly loaded

  • Thread starter Thread starter z f
  • Start date Start date
Z

z f

in a Class Library C# project i make classes and methods public so it can be
called from external module.
in C++ / Win32 a DLL have a DLLMAIN procedure that is being called when the
DLL is loaded.
In a Class Library C# can I have something similar to that?
I want to write code only the first time my Assembly is being loaded. no
matter which of my classes / static methods is being instantiated / called.

TIA.
 
in a Class Library C# project i make classes and methods public so it can be
called from external module.
in C++ / Win32 a DLL have a DLLMAIN procedure that is being called when the
DLL is loaded.
In a Class Library C# can I have something similar to that?
I want to write code only the first time my Assembly is being loaded. no
matter which of my classes / static methods is being instantiated / called.

A difficult question. MS is definite about some things, but the sequencing
of operations is obscure at strategic points like program start and assembly
load.

When I first saw it, I was surprised by the fact that a shared initializer
of mine ran ahead of sub main. It makes some sense, but it was puzzling at
the time. I think you can get what you want with a shared initializer. I'm
using vb jargon because it is what I know.

Consider a class (FirstThingClass) with a shared field (integer iFirstThing)
and a shared initializer (FirstThingInit) that returns an integer (1 sounds
good to me). You should put all your one time stuff in FirstThingInit. In
addition, all the effects of the initialization code should appear as other
shared fields in FirstThingClass. In other words, I don't want you to
initialize shared fields in other classes from code in
FirstThingClass.FirstThingInit. I want FirstThingClass to be self contained
with no side effects to other classes.

The effect of this design will be as follows. Whenever a method (shared or
otherwise) in your dll references a shared public field in FirstThingClass
(which is where ALL the effects of FirstThingInit reside), one of two things
will happen. Either FirstThingInit will already have run, in which case the
method will proceed, or FirstThingInit will not have run, in which case it
will be forced to run ahead of the calling method.

This design won't guarantee that your one-time code will run first, but it
will guarantee that it will run just in time. What do you think?
 
Back
Top