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

前端 未结 3 872
一生所求
一生所求 2021-01-05 10:55

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

3条回答
  •  感情败类
    2021-01-05 11:36

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

        public abstract class CustomViewBase : WebViewPage 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.

提交回复
热议问题