Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically run code on referenced assembly during startup?? What is this called?

Tags:

c#

.net

asp.net

In .NET, there is something that can automatically run a piece of code in a referenced assembly when the assembly is loaded.

For example, you can have a class decorated with a sort of attribute that lives in project Foo(A Class Library). And project Bar(A Web App) simply references project Foo. When Bar loads, that decorated code in Foo gets run somehow. I believe this is a newer feature.

Can someone tell what this feature is called??

Update: Thanks Shiva! Not Module Initialize. Although it lead me to the right answer. PreApplicationStartMethod and it's supported in .NET! Thanks all!!

like image 730
Levitikon Avatar asked Nov 04 '13 19:11

Levitikon


2 Answers

Turns out I was looking for PreApplicationStartMethod! Thanks all!

like image 62
Levitikon Avatar answered Sep 29 '22 09:09

Levitikon


You might have also have a look at Fody. Fody is "an Extensible tool for weaving .net assemblies" which you can install as a nuget package. There is an add-in for fody called Module Initializers. Which under the hood uses the, in other answers already mentioned module initializers, but takes away the plumping.

From the documentation:

What it does: Finds a class, in the target assembly, named ModuleInitializer with the following form:

public static class ModuleInitializer
{
    public static void Initialize()
    {
        //Init code
    }
}

It then Injects the following code into the module initializer of the target assembly. This code will be called when the assembly is loaded into memory

static <Module>()
{
    ModuleInitializer.Initialize();
}
like image 41
Jos Vinke Avatar answered Sep 29 '22 07:09

Jos Vinke