问题
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