Loading classes when an assembly is loaded

O

Outshined

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
 
J

Jon Skeet

Outshined said:
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.AssemblyLoad 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.GetTypes will give you all the types, and Type.TypeInitializer
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
GetCustomAttributes on either the type or the initializer (as a
ConstructorInfo reference) to find out what's there, or just use
IsDefined(typeof(MyCustomAttribute), false).

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

Outshined

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
 
J

Jon Skeet

Outshined said:
Thanks for the helpful reply, Jon.


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.
A very good point - I will take your suggestion.

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

Jon Skeet

Outshined said:
One more clarification:

Yup?

<snip quoted stuff>

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

Outshined

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.AssemblyLoad += new
AssemblyLoadEventHandler(MyAssemblyLoadEventHandler);

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! (e-mail address removed)

K
 
J

Jon Skeet

Outshined said:
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.AssemblyLoad += new
AssemblyLoadEventHandler(MyAssemblyLoadEventHandler);

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! (e-mail address removed)

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.Reflection;
using System.Threading;

public class Driver
{
static void Main()
{
// Make sure we load the assembly containing the custom
attribute
// first! (Loading another assembly within the
AssemblyLoadEvent is
// probably not a good idea.)
Type t = typeof(InitializeOnLoadAttribute);
// Now add the handler
Thread.GetDomain().AssemblyLoad+=new AssemblyLoadEventHandler
(InitializeTypesOnLoad);

Assembly.LoadFrom ("library.dll");
}

static void InitializeTypesOnLoad(object sender,
AssemblyLoadEventArgs args)
{
Assembly loaded = args.LoadedAssembly;

foreach (Type type in loaded.GetTypes())
{
if (type.IsDefined(typeof(InitializeOnLoadAttribute),
false))
{
ConstructorInfo initializer = type.TypeInitializer;
if (initializer!=null)
initializer.Invoke(null, null);
}
}
}
}


Common.cs:
using System;

[AttributeUsage(AttributeTargets.Class)]
public class InitializeOnLoadAttribute : Attribute
{
}


Library.cs:
public class ClassNeedingRegistration
{
// 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 ClassNeedingRegistration()
{
if (!initialized)
{
initialized=true;
Console.WriteLine ("Registering class.");
}
}
}

public class ClassNotNeedingRegistration
{
static ClassNotNeedingRegistration()
{
Console.WriteLine (
"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.)
 

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

Top