Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you inject dependencies into a constructor of a custom WebViewPage, using an IOC container?

In MVC 3, I understand you can create custom WebViewPages. Can you inject dependencies, using constructor injection, via an IOC container?

like image 932
Oved D Avatar asked Oct 05 '11 02:10

Oved D


3 Answers

There is an expample for view injection in a blog post by Brad Wilson http://bradwilson.typepad.com/blog/2010/07/service-location-pt3-views.html

The statements of the others that views allow constructor injection not entirely correct. Yes IDependencyResolver enables creating views that have constructor arguments. But unless you are implementing your own view engine this won't help you at all. Existing view engines like razor will require that you have a parameterless constructor. This means you can do only property injection on views with them.

But as the others said you shouldn't do view injection anyway. Your view should be dumb and just render the view model to HTML. Anything requiring a dependency should be done in the controller or a service.

like image 197
Remo Gloor Avatar answered Oct 22 '22 12:10

Remo Gloor


It is not possible to perform constructor injection. But you can do something like this with, say, Ninject:

    public abstract class CustomViewBase<TModel> : WebViewPage<TModel> where TModel : class
    {
        [Inject]
        public IFace Face
        {
            get;
            set;
        }
    }

And assuming you have set up IDependencyResolver in Global.asax you should correctly have the @Face property initialised. But one important caveat: you may not access @Face in _Layout.cshtml, because (according to Brad Wilson) Layout works outside MVC, and @Face will be null when you try to access it in the layout page.

In any case I agree with the others in that the view should not have to deal with any complex logic.

like image 8
Noel Abrahams Avatar answered Oct 22 '22 11:10

Noel Abrahams


Yes, it is possible, but i really think it is not a good idea. Why would you need some "services" on the view level ? Remember the key MVC guideline - a view must be dumb. In fact, it should be just some sort of template for transformation of view model object to HTML, nothing more.

like image 5
rouen Avatar answered Oct 22 '22 12:10

rouen