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?
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.
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).
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.
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.
Check Module initializers in C#.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With