473,545 Members | 289 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Loading classes when an assembly is loaded

I have a class library where just about every class uses its static
initializer to register with a central registry object in the same assembly.

I am hoping for some sort of Assembly.Load event that I can handle to go
through my assembly and invoke the static initializer on each relevant
class. This way, everything that needs to be registered will be registered
before the first request to the registry object.

So my questions are:

1) Is there an Assembly load event that I can listen for?
2) If so, where would I place the event handler? Any class within the
assembly?
3) Is there a way to iterate though the classes of my assembly and invoke
the static initializers on certain classes?

Thanks in advance,

Wyatt
Jul 19 '05 #1
6 4800
Outshined <so*****@micros oft.com> wrote:
I have a class library where just about every class uses its static
initializer to register with a central registry object in the same assembly.

I am hoping for some sort of Assembly.Load event that I can handle to go
through my assembly and invoke the static initializer on each relevant
class. This way, everything that needs to be registered will be registered
before the first request to the registry object.

So my questions are:

1) Is there an Assembly load event that I can listen for?
There's the AppDomain.Assem blyLoad event which I think is what you're
after.
2) If so, where would I place the event handler? Any class within the
assembly?
You would make your first loaded assembly register an event handler
with the AppDomain, which would then be triggered by any further
assemblies being loaded. You might also want to run all the type
initialisers of the currently loaded assembly too.
3) Is there a way to iterate though the classes of my assembly and invoke
the static initializers on certain classes?


Assembly.GetTyp es will give you all the types, and Type.TypeInitia lizer
will give you all the appropriate type initializers. Personally I'd
suggest marking all types that you want to be handled this way with a
custom attribute - many type initializers may well assume that they're
only going to be called once, but with this scheme you may end up
having them called twice (once automatically when the type is needed,
and once explicitly by yourself). Indeed, my own little experiments
show it being quite hard to make sure that you *do* only call the
initializer once - calling it explicitly seems to call it implicitly
first, if you see what I mean! You may want to keep a static boolean
field which says whether or not you *actually* want to run the
initializer.

Testing for the custom attribute is simple - you either mark the type
or the type initializer itself with the attribute, and then use
GetCustomAttrib utes on either the type or the initializer (as a
ConstructorInfo reference) to find out what's there, or just use
IsDefined(typeo f(MyCustomAttri bute), false).

Let me know if any of this doesn't make sense, and I'll write a sample
program for you.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Jul 19 '05 #2
Thanks for the helpful reply, Jon.
You would make your first loaded assembly register an event handler
with the AppDomain, which would then be triggered by any further
assemblies being loaded.
I'm not clear on the above statement. Where do I place the registration
code? Presumably the event handler itself could reside in my central
registry class.
Personally I'd suggest marking all types that you want to be handled
this way with a custom attribute - many type initializers may well
assume that they're only going to be called once, but with this scheme
you may end up having them called twice (once automatically when
the type is needed, and once explicitly by yourself).


A very good point - I will take your suggestion.

K
Jul 19 '05 #3
Outshined <so*****@micros oft.com> wrote:
Thanks for the helpful reply, Jon.
You would make your first loaded assembly register an event handler
with the AppDomain, which would then be triggered by any further
assemblies being loaded.


I'm not clear on the above statement. Where do I place the registration
code? Presumably the event handler itself could reside in my central
registry class.


The event handler itself could be anywhere that's accessible from where
you want to add it to the AppDomain's event.
Personally I'd suggest marking all types that you want to be handled
this way with a custom attribute - many type initializers may well
assume that they're only going to be called once, but with this scheme
you may end up having them called twice (once automatically when
the type is needed, and once explicitly by yourself).


A very good point - I will take your suggestion.


Goodo. Let me know if you need any sample code for any of this.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Jul 19 '05 #4
Outshined <so*****@micros oft.com> wrote:
One more clarification:


Yup?

<snip quoted stuff>

(I realise there may be another post on its way - this is a prod for
one otherwise!)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Jul 19 '05 #5
One more claification:

As I mentioned, I am building a class library, contained within its own
assembly. If possible, I want to have my library be independent and not
force people to explicitly initialize it before using classes from it. Ergo
my interest in executing initialization when this class library assembly is
loaded. But in order to handle the AppDomain AssemblyLoad event, I must
first register the handler somehow, using the following line:

AppDomain.Assem blyLoad += new
AssemblyLoadEve ntHandler(MyAss emblyLoadEventH andler);

Can this registration occur inside the class library assembly, or must it be
outside - somewhere in the calling application.

I wouldn't mind having that sample code! fu******@yahoo. com

K

"Outshined" <so*****@micros oft.com> wrote in message
news:Sz******** ***********@rwc rnsc51.ops.asp. att.net...
Thanks for the helpful reply, Jon.
You would make your first loaded assembly register an event handler
with the AppDomain, which would then be triggered by any further
assemblies being loaded.


I'm not clear on the above statement. Where do I place the registration
code? Presumably the event handler itself could reside in my central
registry class.
Personally I'd suggest marking all types that you want to be handled
this way with a custom attribute - many type initializers may well
assume that they're only going to be called once, but with this scheme
you may end up having them called twice (once automatically when
the type is needed, and once explicitly by yourself).


A very good point - I will take your suggestion.

K

Jul 19 '05 #6
Outshined <so*****@micros oft.com> wrote:
As I mentioned, I am building a class library, contained within its own
assembly. If possible, I want to have my library be independent and not
force people to explicitly initialize it before using classes from it. Ergo
my interest in executing initialization when this class library assembly is
loaded. But in order to handle the AppDomain AssemblyLoad event, I must
first register the handler somehow, using the following line:

AppDomain.Assem blyLoad += new
AssemblyLoadEve ntHandler(MyAss emblyLoadEventH andler);

Can this registration occur inside the class library assembly, or must it be
outside - somewhere in the calling application.
I believe it must be outside.

Is there a single class which is always going to be used before the
registration is needed? If there is, you could put a call in its static
initializer to do the registration.
I wouldn't mind having that sample code! fu******@yahoo. com


Unfortunately the sample won't handle the above. I don't know of
anything which you can put in an assembly to say, "When this assembly
is loaded, call <x>."

Here it is though, for better or worse. Note that in real code you
would of course handle exceptions, use namespaces, etc.
Driver.cs:
using System;
using System.Reflecti on;
using System.Threadin g;

public class Driver
{
static void Main()
{
// Make sure we load the assembly containing the custom
attribute
// first! (Loading another assembly within the
AssemblyLoadEve nt is
// probably not a good idea.)
Type t = typeof(Initiali zeOnLoadAttribu te);
// Now add the handler
Thread.GetDomai n().AssemblyLoa d+=new AssemblyLoadEve ntHandler
(InitializeType sOnLoad);

Assembly.LoadFr om ("library.dll") ;
}

static void InitializeTypes OnLoad(object sender,
AssemblyLoadEve ntArgs args)
{
Assembly loaded = args.LoadedAsse mbly;

foreach (Type type in loaded.GetTypes ())
{
if (type.IsDefined (typeof(Initial izeOnLoadAttrib ute),
false))
{
ConstructorInfo initializer = type.TypeInitia lizer;
if (initializer!=n ull)
initializer.Inv oke(null, null);
}
}
}
}
Common.cs:
using System;

[AttributeUsage( AttributeTarget s.Class)]
public class InitializeOnLoa dAttribute : Attribute
{
}
Library.cs:
public class ClassNeedingReg istration
{
// Note - this must *not* have =false at the end,
// otherwise it will be set to false every time the type
// initializer is run, before the test for it being false.
// We want the default value (false), but only the first time...
static bool initialized;
static ClassNeedingReg istration()
{
if (!initialized)
{
initialized=tru e;
Console.WriteLi ne ("Registerin g class.");
}
}
}

public class ClassNotNeeding Registration
{
static ClassNotNeeding Registration()
{
Console.WriteLi ne (
"This class does not need to be registered.");
}
}

Compiling:
csc /target:library /out:common.dll Common.cs
csc /target:library /out:library.dll /r:common.dll Library.cs
csc /r:common.dll Driver.cs

Running:
Driver.exe produces output of:
Registering class.

(It only prints it once, even if you call the type initializer multiple
times. It could well be that some of your classes won't need the kind
of guard I've put around it to make sure it only effectively gets
executed once, but I thought I'd show you the pattern anyway.)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Jul 19 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1339
by: Steven Green | last post by:
I came up with this question while reviewing another message in this newsgroup. I've been away on Java for quite a bit and have a question on deletions. I think I already know the answer but I thought I would check with the group to be sure. Why does C++ not call delete for both classes when the pointer is released even when what was...
2
2139
by: Paul Ingles | last post by:
Hi, I have an ASP.NET Web Application which uses a number of controls in an external strongly named assembly. Whenever I view a page that uses one of the controls within the strongly named assembly a FileLoadException is thrown, saying that "The located assembly's manifest definition with name 'CentaurNet.Web.Controls' does not match the...
6
308
by: Outshined | last post by:
I have a class library where just about every class uses its static initializer to register with a central registry object in the same assembly. I am hoping for some sort of Assembly.Load event that I can handle to go through my assembly and invoke the static initializer on each relevant class. This way, everything that needs to be...
4
3120
by: mct | last post by:
Environment --------------- Visual Studio 2005 ..NET 2.0 Windows XP SP2 Scenario ---------- TCLibrary (Class Library) • Contains MyIdentity and MyPrincipal classes that implement the IIdentity
4
1565
by: hyd | last post by:
With C++/CLI - VS2005, is it possible to have static constructors that are automatically called when the owner assembly is loading ? Otherwise, how it is possible to call it without creating an instance of the class or calling a static field of this class ? I need to "register" some classes in a list of classes so that I can create them...
1
979
by: sebastien.varoteaux | last post by:
Hi, I would like to know if it's possible to load classes when IIS starts, or when the first internaut comes load the web application. I would like to automatically load objects in memory (singleton). How can i do that? Best regards,
0
1240
by: John H | last post by:
Hi, Strange error with serialisaation on .net 1.1 Sp1 when a the assembly containing the type is in the Gac as well as on e.g c:\customdlls. ObjValue in below code is populated with and array of classes which are defined in an assembly loaded from c:\customdlls using loadfrom. This same assembly is also in the gac. The below code snippet...
2
2039
by: Jeff | last post by:
Hi I'm trying to achieve a scenario where I have c# files that are compiled dynamically, the assemblies are then loaded in a different AppDomain, I call a simple method from the object, and then unload the AppDomain to release the lock on the assemly files (so to I can compile the code again if it has been modified). However, I've...
4
2669
by: Nicolas R | last post by:
Hi all, Im trying to figure out how to display a 'loading' message when scripts are being executed, ie when the page is still not ready for interaction. This is for a web app which relies on javascript to insert dom elements and do stuff, so the user must know when everything is ready to interact with. I tried using an interval which...
0
7398
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7656
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7416
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7752
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
4944
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3449
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3441
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1878
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
701
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.