Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net: Running code when assembly is loaded

Is it possible to run some code when an assembly is loaded, without doing anything specific in the loading code? What I am looking for is like a static constructor on a type.

Eg:

Assembly A does not know about Assembly B, but B does know about A. Assembly A needs to know certain things about B if B is loaded. When Assembly B is loaded by the runtime (referenced, or explicit), I want a piece of code (static method or attribute) to be executed that calls a method in Assembly A.

The root cause of this problem is unknown types being encountered when serializing a type in A that contains types from B not known at compile time as interfaces are used.

like image 321
Robert Wagner Avatar asked Feb 02 '09 22:02

Robert Wagner


People also ask

How does .NET resolve assembly references?

If the runtime determines that an assembly matches the calling assembly's criteria, it uses that assembly. When the file specified by the given <codeBase> element is loaded, the runtime checks to make sure that the name, version, culture, and public key match the calling assembly's reference.

How does assembly load work?

Loads an assembly given its AssemblyName. The assembly is loaded into the domain of the caller using the supplied evidence. Loads the assembly with a common object file format (COFF)-based image containing an emitted assembly. The assembly is loaded into the application domain of the caller.

How does assembly work C#?

An assembly is a file that is automatically generated by the compiler upon successful compilation of every . NET application. It can be either a Dynamic Link Library or an executable file. It is generated only once for an application and upon each subsequent compilation the assembly gets updated.

Where are .NET assemblies located?

An assembly can be found mostly in either of the following places: GAC - C:\Windows\Assembly\GAC (Microsoft provided and by third-party in some cases)


2 Answers

The CLR supports module initializers. You'd have to hack C++/CLI code or ilasm.exe to use them.

UPDATE: directly supported in C# as well since .NET 5 with the [ModuleInitializer] attribute

like image 59
Hans Passant Avatar answered Sep 24 '22 09:09

Hans Passant


You can use static constructors in .Net, but unfortunately they don't do what you want. Static constructors are only executed just before a type is used. See http://msdn.microsoft.com/en-us/library/k9x6w0hc(VS.80).aspx for details.

You might get some mileage from subscribing to your AppDomain's AssemblyLoad event. See http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyload.aspx.

In your event handler you could reflect on the newly loaded assembly, and get it to execute whatever code you like.

like image 39
Antony Perkov Avatar answered Sep 20 '22 09:09

Antony Perkov