问题 整个程序集的静态构造函数


我的程序集中有很多入口点,我希望在运行此程序集中的任何其他代码之前,每个AppDomain执行一次初始化代码。最好的方法是什么?

我看到的一个解决方案是拥有一个带有静态构造函数的类,并继承我拥有的每个入口点。像这样的东西:

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.

这让我可以避免在每个入口点编写样板静态构造函数,但是没有多继承,这并不总是可行的。你能想到其他更好的选择吗?


5361
2017-08-08 08:16


起源

msdn.microsoft.com/en-us/library/... - Jaroslav Jandek
请说明是否要执行“每个程序集一次”或“每个AppDomain一次”的代码。请记住,AppDomain中可以有许多程序集,并且根据程序集甚至可以在程序集之间共享(仅加载一次)。 - Manfred


答案:


检查 C#中的模块初始值设定项


11
2017-08-08 08:25



很高兴知道,谢谢! - Konstantin Spirin