13

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?

starblue
  • 55,348
  • 14
  • 97
  • 151
Konstantin Spirin
  • 20,609
  • 15
  • 72
  • 90
  • http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyload.aspx – Jaroslav Jandek Aug 08 '10 at 08:20
  • Please clarify whether you want to execute code "once per assembly" or "once per AppDomain". Remember that there can be many assemblies in an AppDomain and depending on the assembly it may be even shared between assemblies (loaded once only). – Manfred Aug 08 '10 at 08:37

1 Answers1

12

Check Module initializers in C#.

Incognito
  • 16,567
  • 9
  • 52
  • 74