How to dependency injection using Ninject in View in MVC 3? I am now using Ninject 2.2 and Ninject.MVC3 2.2.2.0
-
It would help if you were to explain what you want to do. Chances are, there is a better way to do it than what you think you have to do. Injecting code into the view is so far beyond a bad practice that you have to be going down a wrong path to even want to do it.Erik Funkenbusch– Erik Funkenbusch2011-07-16 21:44:27 +00:00Commented Jul 16, 2011 at 21:44
Add a comment
|
2 Answers
You shouldn't be using Ninject to supply anything to the View. Ninject supplies dependencies to the Controllers, it is the job of the controller to build and pass models required by the View.
There are plenty of good tutorials around, see here for example.
3 Comments
Hieu Nguyen Trung
what else if i want to manually write code straight to the View using some service?
Remo Gloor
Why do you want to do this? It's generally considered as bad practice. So why to you want to do a bad practice if anyone would tell you not to do so?
Hieu Nguyen Trung
Because i have some partial view, that always come through the website, but i think it's not a good idea to get the data from database from all the controller to render it, i want to separate it, is there any other way instead of writing straight to the view?
Take a look on previous answers, do you really need this? View injection is in contradiction with MVC pattern and should be avoided in most cases.
But if you need some service to render some parts of a view you can do following:
DependencyResolver.Current.GetService<IViewService>(), but I don't recommend to do this way as this is well known "service locator" antipattern.- Here I found a better approach