"Model bound complex types" Error in ASP.NET Core 2

I'm presently working on an ASP.NET Core 2 Project. To be honest, it's my first real project with the tech stack. Most have gone smoothly and I've found some great utility in the included libraries.

Among them is Dependency Injection (Microsoft.Extensions.DependencyInjection)... something where I've previously used Unity.

Anyway, while doing my unit tests, one thing I tend to do is (over) use interfaces. For existing or generated types, I take the concrete classes and convert them to interfaces. The purpose is to universally mock out all of my inputs.

Upon completing a unit test, I found that at run time I received the following error:

Model bound complex types must not be abstract or value types and must have a parameterless constructor.

This post is to briefly explain this message in this context which should help others that run in to this issue as well as remind me should I return to this question.

Details can be found here, but the bottom-line is it has to do with how the DI system determines which dependency to inject (and perhaps, how to populate it). Ultimately, the stock implementation can't determine which dependency to load up and inject on an interface. If you put the [FromServices] attribute on the parameter in question, the variable will resolve but it is not populated.

A solution (workaround?) can be found here: http://www.dotnet-programming.com/post/2017/03/17/Custom-Model-Binding-in-Aspnet-Core-2-Model-Binding-Interfaces.aspx

I've elected to not use this workaround for the time being. This could change in the future but for now I've decided to not make ViewModels to be interfaces. It's an unnecessary complication.

Frank Villasenor

Frank Villasenor

Owner and principal author of this site. Professional Engineering Lead, Software Engineer & Architect working in the Chicagoland area as a consultant. Cert: AWS DevOps Pro
Chicago, IL