0

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.

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();
    }
}
4
  • are you requesting foo or Ifoo ? because your binding is only to foo Sep 14, 2015 at 19:16
  • requesting foo every where
    – bidva
    Sep 14, 2015 at 19:18
  • @bidva That seems a bit off. There's no real benefit to binding to a concrete class AND incurring the overhead of DI (particularly Ninject's overhead) since you lose the ability to code to contract instead of concrete implementation.
    – David L
    Sep 14, 2015 at 19:24
  • @DavidL ok is it possible show me how can I make only one instance of foo? I need only one foo in my project how can i injected just one foo into other classes
    – bidva
    Sep 14, 2015 at 19:36

2 Answers 2

0

To tell Ninject to Bind the class in a singleton scope:

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. Create Standard Kernel instance in your DefaultNinjectModule,

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

check this link for reference & customization: Object scopes

0

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:

kernel.Get<Ifoo>();

This will get you your single instance of 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. In your unload do:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.