Question

I'm currently developing business logic in a Controller's ActionResult function, and I've noticed it's becoming unwieldy... large... involves a lot of page ups/downs.

Code includes populating lists for dropdownlists assigned to ViewBag properties, but most of the size is taken up EF (linq to entities) and in memory processing of this. And finally sent to a view model via Auto Mapper.

Where is the best place to move this code? In another class in the Controllers folder? Or in another class in another folder, i.e. a Business layer?

Was it helpful?

Solution

Separate you project to :

  • WebUI(View, Controller-A MVC Project)
  • Business Layer(Holds Business Logic - A class Library Project )
  • Data Access Layer(Holds Entity Model(May be EDMX) - A class Library Project)

A controller of WebUI project call method of business layer. If business need data from database then, it will call Data Access Layer.

OTHER TIPS

Funnily enough I answered a very similar question yesterday. In a nutshell, limit your controller to just the minimum logic to link your models with your views. Business logic, data access etc. is better placed in a separate repository.

Bappi Datta is right. Let me just explain it from my point of view.

My best practice with the libs AutoMapper, EF is:

  • Web - includes logic of rendering, some validation, bootstrap configuration. Calls Business layer methods and classes.
  • Web.Models - web models with validation attributes
  • BusinessLogic - business layer. Includes mappings EF Entities <---> Web.Models. Uses Data classes.
  • Data - Here I always put EF Models and context. Also implementation of Repository pattern could be placed there.

You need to have Repository Layer (which you mentioned you already have) and then you need to have a Service Layer which will hold all your necessary business logic probably using patterns like Command Factory and Facades. Then in order for you to have a flexible and easily pluggable architecture, you need to use Dependency Injection between all layers.

Read about MVC architecture in my perspective

There can be different If's and But's in the theoretical discussion of overall MVC architecture itself. But generally your controller actions needs to be thin, you business logic needs to be in a different layer other than repository.

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top