ASP.NET MVC Business Logic in Domain Model vs Service Layer

emre nevayeshirazi picture emre nevayeshirazi · Feb 2, 2013 · Viewed 19.5k times · Source

I have been reading about where to put business logic in ASP.NET MVC Project for a while and I still can't get clear on some things.

1 - Domain models. What are these really? In my Model folder I have only a bunch of classes corresponding to my database. I am using EF code first. I assume these are my domain models.

2 - Service Layer. This answer suggests a service layer and I think this makes perfect sense. I had decided to go with this one. However, Martin Fowler's "Anemic Domain Models" article messed up my mind.

I am not really sure how can I add logic to my domain models.

I have gone through many business logic-related questions and each of them proposes either 1 or 2. What I don't understand is how I can implement the first one. Adding methods to entity classes (domain models for me) does not make sense at all. And why is the second approach considered bad?

Answer

Martin picture Martin · Feb 2, 2013

First off, your Model folder in your Asp.Net MVC project should be used for ViewModels. These are the models that your Controllers send to your Views. They should be highly optimized for the View, meaning only the properties needed for the view, and nothing else.

What you are taking about, Domain Models, are the same as Business Models, and belong in your Business Layer. The Model folder in your Asp.Net MVC project are the models for your UI Layer.

The second approach, business logic in your service (really business) layer is not considered bad. It's a very nice buffer between your Data Layer and your UI Layer (3-tier architecture). Your data layer handles getting data, from either web services or a database, and your business/service layer handles translating that data into business/domain models. It also holds any business logic, like calculations, etc.

These business/domain models are usually POCOs, but they don't have to be. This is how I sometimes set up my business models:

public class BusinessObject
{
    private DataObject _dataObject;

    public BusinessObject(DataObject dataObject)
    {
        _dataObject = dataObject;
    }

    public int BusinessId
    {
        get {return _dataObject.Id;}
        set {_dataObject.Id = value;}
    }

    public string Name
    {
        get {return _dataObject.Description;}
        set {_dataObject.Description = value;}
    }
}