473,385 Members | 1,353 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

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 4784
Outshined <so*****@microsoft.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.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.

--
Jon Skeet - <sk***@pobox.com>
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*****@microsoft.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.com>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Jul 19 '05 #4
Outshined <so*****@microsoft.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.com>
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.AssemblyLoad += new
AssemblyLoadEventHandler(MyAssemblyLoadEventHandle r);

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*****@microsoft.com> wrote in message
news:Sz*******************@rwcrnsc51.ops.asp.att.n et...
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*****@microsoft.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.AssemblyLoad += new
AssemblyLoadEventHandler(MyAssemblyLoadEventHandle r);

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.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.)

--
Jon Skeet - <sk***@pobox.com>
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
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...
2
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...
6
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...
4
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...
4
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...
1
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...
0
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...
2
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...
4
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...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.