Hey guys,
Damian Edwards told me to log this concern here, so that's what I'm doing.
Right now when a ViewModel needs to be DI resolved, we've had to basically copy/paste your ComplexTypeModelBinder and change the ModelCreation to be ServiceProvider resolved instead of newed up manually. I think it would make sense for this to be the default behavior in your model binder. You can see our implementation here:
You should be able to subclass ComplexTypeModelBinder and just override CreateModel(...) https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Core/ModelBinding/Binders/ComplexTypeModelBinder.cs#L314
Would that meet your needs?
Certainly, that is the right way to do that... updated that code, but that doesn't really answer the question. Why is this not the default implementation? It makes the binder be able to do more without any consequence that I can see.
This is not the default implementation because it would require you to register all of your model types in DI.
That's a good point, but an easy solution for that is to default to resolving any non-interface type with itself. So if its it's an unregistered class that needs to be resolved, then just use that same class to do the resolving. Only throw an exception if there is no registration for an interface type.
@Serjster what's the concrete scenario DI viewmodels enable? I'm curious.
You can see in this example:
https://github.com/Serjster/IOCModelBinderExample/tree/ASPNETRTMVersion
1) Allows my controllers to be uber clean.
2) The Controller doesn't need to know anything about the needs of the ViewModel. This prevents the mixing of responsibilities.
Why was this closed?
@danroth27 So is there any official "out-of-the-box" solution in NET Core 1.0.1 ? Or do we still need to do solution with ComplexTypeModelBinder ?
Using the ComplexTypeModelBinder solution is the way to go. We are not planning to add this behavior.
Most helpful comment
You can see in this example:
https://github.com/Serjster/IOCModelBinderExample/tree/ASPNETRTMVersion
1) Allows my controllers to be uber clean.
2) The Controller doesn't need to know anything about the needs of the ViewModel. This prevents the mixing of responsibilities.