Murilo
Murilo

Reputation: 1152

Correct way to use a controller and deal with business logic

I'm having trouble in how to write my ASP.NET MVC application, mainly in how to use my business logic. I will provide just some example. I don't know if this is right:

public class UserController {
   public ActionResult Create(User user){
      UserService service = new UserService();
      if(!service.UserExists(user.Email)){
        if(service.InsertUser(user)){
           service.SendConfirmation(user);
         }
      }
   }
}

Or this is right

public class UserController {
   public ActionResult Create(User user){
      UserService service = new UserService();
      service.CreateUser(user);
   }
}

In this second example the method CreateUser of UserService will check if user exists, then will insert, then will send the email.

The main difference is that in the second example the controller calls only one method while in the second it calls many methods and receives answers, in both cases the logic is inside UserService.

What's correct?

Upvotes: 0

Views: 71

Answers (1)

Florian Schmidinger
Florian Schmidinger

Reputation: 4692

The second one is the one to choose. It utilizes proper encapsulation. The controller should not do logic but communicate with the services and feed the views with the data and manage program flow.

however you should receive some response from your service.

In your example it could mean some enum value or a boolean value to determine if the creation of the user was successfull or anything... on this you can then let the controller manage what view comes next and what data it gets...

Upvotes: 4

Related Questions