我可以 运行 在 linqpad 中每个进程只执行一次函数吗?

Can I run a function only once per process in linqpad?

我有一个 Ninject IoC 容器,它有很多绑定。我在我的 linqpad 脚本中绑定。

但是,当我多次尝试 运行 时,这失败了,因为在第二个 运行 上,相同类型有多个绑定,所以当我尝试从 IoC 获取时容器失败。

是否有我从 Ninject 使用的应用程序启动或初始化函数,以便绑定只发生一次?

例如,在 MVC 程序中,我会使用 Application_Start()

示例:在此程序中,每次程序 运行 输出计数都会增加。是否有我可以挂钩以重置计数的应用程序启动事件?

我的实际需要是防止 ninject 内核的双重绑定,所以请不要 "solutions" 修复单例,我知道它不是线程安全的等等!

void Main()
{
    {
        var x = Singleton.Instance;
        Console.WriteLine(x.count++);
    }
}

// Define other methods and classes here

public class Singleton
{
    private static Singleton instance;

    private Singleton() { }

    public int count;

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Singleton();
                instance.count = 0;
            }
            return instance;
        }
    }
}

我没有意识到 LinqPad 中的静力学会发生这种情况。好发现。

您是否尝试过在 Singleton class 中用标志包装对 Application_Start() 的调用,其方式类似于您使用 if(instance == null).

类似...

private static bool _initialised;
public static void Initialise()
{
    if(_initialised)
      return;
    _initialise = true;
    something.Application_Start();
}