Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static constructor for the whole assembly

I have many entry points in my assembly and I want some initialization code to be executed once per AppDomain prior to running any other code from this assembly. What would be the best way to do it?

One solution I see is to have a class with static constructor and inherit every entry point I have from it. Something like this:

public class Initializer
{
    static Initializer()
    {
        EnsureInitialized();  // Calls initialization code once and only once
    }
}

public class EntryPointOne : Initializer, IEntryPoint
{
    // Some code here
}

public class EntryPointTwo : Initializer, IEntryPoint
{
    // Some code here
}

// etc.

This lets me avoid writing boiler plate static constructors in every entry point but without multi-inheritance this is not always possible. Can you think of any other better options?

like image 545
Konstantin Spirin Avatar asked Aug 08 '10 08:08

Konstantin Spirin


People also ask

What is static constructor with example?

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed only once. It is called automatically before the first instance is created or any static members are referenced. C# Copy. class SimpleClass { // Static variable that must be initialized at run time.

Can we have multiple static constructor?

A class or struct can only have one static constructor. Static constructors cannot be inherited or overloaded. A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR).

How many times of static constructor executes for a class?

Times of Execution: A static constructor will always execute once in the entire life cycle of a class. But a non-static constructor can execute zero time if no instance of the class is created and n times if the n instances are created.

What is static constructor in C++?

A static constructor is used to initialize static data of a class. C++ doesn't have static constructor. But a static constructor can be emulated by using a friend class or nested class as below.


1 Answers

Check Module initializers in C#.

like image 111
Incognito Avatar answered Oct 05 '22 23:10

Incognito