如何确保 InSingletonScope 只使用一个实例

how to ensure InSingletonScope using only one instance

我只想在我的代码中有一个 foo 实例,但每次它创建新实例时都使用此配置,每次涉及构造函数时我都检查过,但我不明白为什么。

public sealed class foo: Ifoo
    {
        public string Test { get; set; }
        public foo()
        {
            this.Test = "test";
        }
    }

我的容器是这样的

public class DefaultNinjectModule : NinjectModule
{
      public override void Load()
    {
         this.Bind<foo>().ToSelf().InSingletonScope();
    }
}

告诉 Ninject 在单例范围内绑定 class:

kernel.Bind<foo>().ToSelf().InSingletonScope();

This behaviour will only work for instances requested from the Kernel.

在您的情况下,它是由 DefaultNinjectModule(this) 而不是内核请求的。 在您的默认 Ninject 模块中创建标准内核实例,

var kernel = new StandardKernel();
kernel.Bind<foo>().ToSelf().InSingletonScope();

检查此 link 以供参考和自定义: Object scopes

您应该将您的界面绑定到您的 class:

public override void Load()
{
    this.Bind<Ifoo>().To<foo>().InSingletonScope();
}

然后当你想要 foo 时使用:

kernel.Get<Ifoo>();

这将为您提供 foo 的单个实例。

注意:如果您有从 IDisposable 派生的单个实例 class,则必须释放您的单个实例,Ninject 不会为您执行此操作。在你的卸载中做:

public override void Unload()
{
    this.Kernel.Get<Ifoo>().Dispose();
    base.Unload();
}