How to split out a service layer

asp.net-mvcentity-framework

I currently have four projects in my website's solution:

Project.Data
This holds the EntityFramework DbContext object and also the Repositories that interact with it. It references Project.Models.

Project.Models
This holds the business objects and doesn't reference any other project

Project.Web
This holds all ViewModels, Views, Controllers and static website content. It references Project.Data (for the Repositories), Project.Models and Project.Service

And now I get to the problem project…

Project.Service
I want this to be the project that Project.Web uses to make its controllers thin, as I understand this is desirable.

Each of the classes in this project will probably have a repository injected into it so they can access any data they need to. One of their responsibilities will be to create a ViewModel for the controllers in Project.Web to use. This means that it will reference Project.Data for a reference to those repositories, Project.Models for the models and Project.Web for access to the ViewModels.


So just as I'm getting the feeling I'm doing something really wrong by all this, I go to add my last reference to Project.Web from Project.Service and it errors out telling me that I now have a circular dependency…

What exactly am I doing wrong here? Are there patterns I can use that will clean up some dependencies on other projects or am I trying to do something that isn't useful anyway?

Best Answer

I think what you're trying to create is:

Data => Services => Controller | VM => View

But what you're setting up isn't lending itself to that.

As Jimmy Hoffa points out, you need to think of your end-points. It's not clear to me exactly what roles you're intending with your existing project names. So I'll provide my answer using slightly different descriptors. Plug your projects in as appropriate.

Your Data Access Layer(DAL) is an endpoint, as is your Views.

Views will reference the Controller | ViewModel project.

Controller | VM project will reference your Model and / or Services project. Which one(s) depends upon your terminology.

If you have a Model, it will reference your Services project.

Finally, the Services project will reference your DAL.