24

Well, this question is pretty simply stated by the title.

For a local variable factory:

var factory = Fluently.Configure()
...

Are these two lines equivalent:

Bind<ISessionFactory>().ToConstant(factory).InSingletonScope();

and:

Bind<ISessionFactory>().ToConstant(factory);
joshperry
  • 41,167
  • 16
  • 88
  • 103

1 Answers1

25

In the latest version of ninject, when you create a ToConstant binding it will automatically set the Scope to Singleton. Thus, the InSingletonScope() part in your example is redundant. From ninject code base:

    /// <summary>
    /// Indicates that the service should be bound to the specified constant value.
    /// </summary>
    /// <param name="value">The constant value.</param>
    public IBindingWhenInNamedWithOrOnSyntax<T> ToConstant(T value)
    {
        Binding.ProviderCallback = ctx => new ConstantProvider<T>(value);
        Binding.Target = BindingTarget.Constant;
        Binding.ScopeCallback = StandardScopeCallbacks.Singleton;

        return this;
    }
Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
Andrew Savinykh
  • 25,351
  • 17
  • 103
  • 158
  • Thanks for digging into the code for me :) I'm using 2.2.1.2 (newest from NuGet) which does not have the `Binding.ScopeCallback` assignment. Is that just for internal houskeeping or does that mean I'll still need to specify `InSingletonScope` until we update to the latest version? – joshperry Sep 13 '11 at 04:47
  • My opinion is that you better specify it explicitly in any case. It makes your intention more clear and protects you if default changes. – Andrew Savinykh Sep 13 '11 at 06:53
  • I do agree about being explicit, but I think binding to a "Constant" quite explicit describes my intention for that exact instance of an object to be the only result to this binding. The only semantic difference I can see with `InSingletonScope`, perhaps with an `OnActivate` callback for setup, is that the instance won't be created until the point that a request for the type in the binding is fulfilled. – joshperry Sep 13 '11 at 18:58
  • Scope affects caching and activation. While net effect for `ToConstant` *seems* to be the same regardless, if you do performance tests, for example, you'll notice that there maybe difference between `InSingletonScope` and `InTransientScope` because caching code being executed is different. – Andrew Savinykh Sep 13 '11 at 21:49