stylishCoder
stylishCoder

Reputation: 385

Why we use .ToSelf() in ninject what's the main logic behind that

I am working on Ninject as new i have one queestion from below code in Class "Warrior Module" we have bindeed interface with class thatis understood but why we use .ToSelf() with class SWORD I have done google but i cant get the exact logic behind this..what if i remove the line

Bind<Sword>().ToSelf();

Below Code

//interface
        interface IWeapon
        {
            void Hit(string target);
        }
        //sword class
        class Sword : IWeapon
        {
            public void Hit(string target)
            {
                Console.WriteLine("Killed {0} using Sword", target);
            }
        }

         class Soldier
        {
            private IWeapon _weapon;
            [Inject]
            public Soldier(IWeapon weapon)
            {
                _weapon = weapon;
            }
            public void Attack(string target)
            {
                _weapon.Hit(target);
            }
        }

         class WarriorModule : NinjectModule
        {
            public override void Load()
            {
                Bind<IWeapon>().To<Sword>();

                Bind<Sword>().ToSelf();//why we use .Toself() with self
            }
        }

        static void Main(string[] args)
        {
            IKernel kernel = new StandardKernel(new WarriorModule());

            Soldier warrior = kernel.Get<Soldier>();

            warrior.Attack("the men");

            Console.ReadKey();
        }

Upvotes: 3

Views: 1968

Answers (1)

BatteryBackupUnit
BatteryBackupUnit

Reputation: 13233

Ninject allows resolution of "self-bindable" types even if they have no explicit binding.

It then defaults to the equivalent of

Bind<Foo>().ToSelf()
    .InTransientScope();

Note:

  • The ToSelf() binding is equivalent to Bind<Foo>().To<Foo>().
  • When you don't specify a scope it defaults to InTransientScope(). So when you write Bind<Foo>().ToSelf(); that is also equivalent to Bind<Foo>().ToSelf().InTransientScope();

Conclusion

In conclusion you only need to write a binding for a self-bindable type if you want it to be different from the default, for example:

Bind<Foo>().ToSelf()
    .InRequestScope();

or

Bind<Foo>().ToSelf()
    .OnActivation(x => x.Initialize());

or

Bind<Foo>().To<SpecialCaseFoo>();

I also think that at some point there was (or still is) an option to deactivate the "self-binding" auto-binding behavior, in which case a Bind<Foo>().ToSelf() can make sense, too.

Upvotes: 6

Related Questions