Two MVC projects(API and Web), should ViewModel be in a common library or in each project

asp.net-mvc

I'm creating a .NET MVC solution that will have two web projects, one for API and for Web. Some models, such as customer, will be the same between the two projects.

Is it best to have them kept in a common web library and referenced from the two web projects, or keep them unique to each project?

Best Answer

It's tempting to ruthlessly eliminate duplication in our systems, and for very good reasons, but we must always ask ourselves whether this is real duplication or apparent duplication.

What I mean is that we'll sometimes have code that looks identical, but each will have their own reason to change, independent of each other. If you think the view model for the App will always change in tandem with the view model for the API, then they should share the same view models. However, you'll likely soon find that the view model for your app needs a property that the API doesn't need, due to needing some ephemeral UI element (like, say... a drop down list that contains data from some external system you'll be "borrowing" in your app).

I see the app and the API as two different front ends to the same business models. They should absolutely share the same business models (logic/dtos), but sharing view models is iffy at best IMO. If things are identical now, you could share the code, then inherit from your shared classes later, if you run across a situation where you need to extend the base models. Maybe the best of both worlds.