[英]how to ensure InSingletonScope using only one instance
I want to have only one instance of foo in my code but with this configuration each time it create new instance and I checked every time it comes to constructor and I can't understand why. 我只想在代码中包含一个foo实例,但每次创建新实例时都使用此配置,每次使用构造函数时我都进行检查,但我不明白为什么。
public sealed class foo: Ifoo
{
public string Test { get; set; }
public foo()
{
this.Test = "test";
}
}
my container is like this 我的容器就是这样
public class DefaultNinjectModule : NinjectModule
{
public override void Load()
{
this.Bind<foo>().ToSelf().InSingletonScope();
}
}
To tell Ninject to Bind the class in a singleton scope: 告诉Ninject在单例范围内绑定类:
kernel.Bind<foo>().ToSelf().InSingletonScope();
This behaviour will only work for instances requested from the Kernel .
此行为仅适用于从内核请求的实例。
In your case it is requested by the DefaultNinjectModule( this
) & not the kernel. 在您的情况下,它是由DefaultNinjectModule(
this
)请求的,而不是内核的请求。 Create Standard Kernel instance in your DefaultNinjectModule, 在您的DefaultNinjectModule中创建标准内核实例,
var kernel = new StandardKernel();
kernel.Bind<foo>().ToSelf().InSingletonScope();
check this link for reference & customization: Object scopes 检查此链接以获取参考和自定义: 对象范围
You should bind your interface to your class: 您应该将接口绑定到您的类:
public override void Load()
{
this.Bind<Ifoo>().To<foo>().InSingletonScope();
}
Then when you want foo you use: 然后,当您想要foo时,可以使用:
kernel.Get<Ifoo>();
This will get you your single instance of foo. 这将使您获得foo的单个实例。
Note: If you have a single instance class derived from IDisposable, you must dispose your single instance, Ninject doesn't do this for you. 注意:如果您具有从IDisposable派生的单个实例类,则必须处置单个实例,Ninject不会为您执行此操作。 In your unload do:
在您卸载时:
public override void Unload()
{
this.Kernel.Get<Ifoo>().Dispose();
base.Unload();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.