C# – How to organize code based on functionality

centerprise-architecturemvc

I use MVC + service classes in my project. My projects structure looks like this:

-MySolution.Web
-MySolution.Models
-MySolution.Services
-MySolution.Common

MySolution.Web is an asp.net web application project. MySolution.Models stores model classes that map directly to database by using Entity Framework. MySolution.Services is where I keep all the business rules and retrieve data from database.

MySolution.Web uses MySolution.Services to get mapped data from database and displays it, e.g. in my controller I call _customerService.GetActiveCustomers().

This works well for retrieving database related entities, but I have a dilemma where to put classes that have nothing to do with database and do other things. Here is example:

I need to get a couple of articles from a website and display information. I could have classes such as ArticlesRepository, Article, ArticleParagraph, etc. Now, I could put them in MySolution.Services and MySolution.Models, but this will very quickly clutter theses projects.

I was thinking about creating new project for this called MySolution.Articles that would be referenced by MySolution.Web. Now, there are only 3 classes and I don't know if making a whole project for this is a good idea.

Best Answer

For Enterprise Architecture, you can follow the conventions that are widely adopted by developers around the world. The propose is you to use the N-Layered Architecture separeted by concerns, the main layer is the Domain Model, following by Data Access Layer (DAL), the Business Logic Layer (BLL) and the Presentation or GUI, where you put your user interfaces.

The problem that you've mentioned, could easily be solved by adding a exclusively layer to care about the Database (the Data Access Layer), your current Models layer, should have just the entities, values object, relations and business rules.

The Business Layer (you named it MySolution.Services, and it's a good name), is responsible for link the Data with the Models, and deliver it to the presentation layer, that you named it MySolution.Web.

If you'd like it, you can read more about Enterprise Architecture, and I recommend to you read about Domain-Driven Design by Eric Evans and Enterprise Architecture by Martin Fowler.

Remember, there's not a template for architecture, your decisions should be guided by the problem domain that you are trying to solve.

I hope it been useful for you, think about it and good code!

Related Topic