Ninject: What does it mean to bind something to itself?
Asked Answered
D

2

8

Ninject has the functionality of self binding like Bind<Samurai>().ToSelf();

I read about this but I don't get the importance or how this can be useful. Any comments are appreciated.

Dennison answered 9/5, 2014 at 7:40 Comment(0)
C
8

If Ninject finds a object that needs to be created and it has a constructor that has a Samurai parameter it does not know how to instantiate it.

But when you use Bind<Samurai>().ToSelf(); then Ninject knows that a Samurai needs to be created to pass to the Samurai parameter.

If that binding was not there then ninject didn't know what to pass, for example there might have been a SamuraiSubClass type. But by explicitly saying that when Ninject finds a Samurai parameter that it needs to create a Samurai for that parameter then Ninject knows exactly what to do.

Cynewulf answered 9/5, 2014 at 7:45 Comment(4)
Why not just explicitly say what to bind Samurai ?Guyon
Bind<Samurai>().To<Samurai>(); is the same as Bind<Samurai>().ToSelf(); it just reads betterCynewulf
Ok I see so it is not just interfaces that you can inject you can also inject concrete typesGuyon
Indeed, or abstract classesCynewulf
B
3

I use the .WithConstructorArgument() quite a bit. Bind<Samurai>().ToSelf().WithConstructorArgument("owner", user); Just a nice way to provide an object(s) to your Samuari constructor when it is being injected.

Bessette answered 17/5, 2014 at 2:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.