Does ASP.NET MVC allow private ViewModel constructor?

前提是你 提交于 2019-12-23 08:59:37

问题


The question is, as in title, whether the MVC model binder allow private constructors for the view model objects. Apparently it doesn't, saying MissingMethodException: No parameterless constructor defined for this object. even if there is a private parameterless constructor. In case if there is no private constructor allowed, is there an arhitectural workaround?

Such constructor might be useful to ensure that only the model binder could create ViewModel objects whose fields might not be consistently filled - there would be no chance that in other parts of code some fields are forgotten to complete.

Entity Framework, in a similar situation, can use private constructor and private properties.


回答1:


No, it does not.

If you want to prevent actual code from calling that constructor, you can add [Obsolete("For model binding only", true)] to a public constructor. This will cause a compiler error if the constructor is explicitly called.




回答2:


You can always write a custom model binder that does support private/protected ctors.



来源:https://stackoverflow.com/questions/12219305/does-asp-net-mvc-allow-private-viewmodel-constructor

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