简体   繁体   中英

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?

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM