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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With