7

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.

Lorlin
  • 844
  • 5
  • 15
  • Related: [Is it possible to have a non-public parameterless constructor that can be used for model binding?](https://stackoverflow.com/q/44261895/993547) – Patrick Hofman May 30 '17 at 12:28

2 Answers2

17

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • This is so hidden it's taken me months to find this solution. This answer needs to be on the more popular "no parameter less constructor defined" thread. Thank you. – Martin Dawson Jul 13 '16 at 01:04
1

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

Paul Hiles
  • 9,558
  • 7
  • 51
  • 76