Ninject: What does it mean to bind something to itself?

断了今生、忘了曾经 提交于 2019-12-07 02:55:00

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/23559120/ninject-what-does-it-mean-to-bind-something-to-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!