mikemanne
mikemanne

Reputation: 3575

Encapsulating ASP.NET MVC models as reusable assembly

Is there an accepted/expected best-practice way to encapsulate the "model" portion of ASP.NET MVC into a re-usable assembly?

As a technical exercise, I want to use the same business/persistence layer within different systems. For example, compile the same assembly into both an ASP.NET MVC app, and a traditional Windows service.

My thinking is to implement my models (and EntityFramework / DbContext / etc) in a separate assembly. Then my MVC project would omit the "Models" folder entirely, and my Controllers would reference the code in the "models assembly". I've always preferred ViewModels over actual business objects as the "targets" of Views, so I'm perfectly happy to have all my Views strongly-typed to ViewModel objects instead of Model objects anyway.

  1. Is this a common approach?
  2. Does it violate the "convention over configuration" tenet of ASP.NET MVC?
  3. Are there specific MVC benefits that I'd be losing, by going with this approach?
  4. Are there other nasty pitfalls to this approach?

I'm a reasonably comfortable veteran of ASP.NET, C#, and windows services, but quite novice to ASP.NET MVC. Apologies if this is a duplicate question; most of the "reusable MVC" questions focus on the UI components, and not the entire business/persistence "layer". As always, thanks in advance for your insights!

Upvotes: 2

Views: 624

Answers (1)

Jeremy McGee
Jeremy McGee

Reputation: 25200

Yes, it's how I've seen many systems developed. You end up with a "business tier" which can work just as well with REST-over-WCF-on-IIS as with anything else.

No, you don't lose anything that I know of, although there's a slight added complexity of maintaining multiple projects.

The other advantage of this is that you end up with controllers and a model layer that are both more testable as you can use dependency injection between them.

Upvotes: 2

Related Questions