我应该在哪里将控制器业务逻辑放在MVC3中

Ger*_*ldo 22 asp.net-mvc

我理解MVC就是把事情放在正确的位置和逻辑应该是什么.我的控制器操作充满了业务逻辑(与数据存储无关),我觉得我应该开始将一些逻辑移到另一个地方.

是否存在我应该放置这种逻辑的约定?例如,我有以下控制器位于控制器文件中:

adminPowerController 

  public ActionResult Create(string test1)
    // business logic
    // business logic
    // business logic
    return View();
  }
  public ActionResult Index(string test1)
    // business logic
    // business logic
    // business logic
    return View();
  }
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 28

建议将业务逻辑放入服务层的位置.因此,您可以定义一个代表业务操作的接口:

public interface IMyService
{
    DomainModel SomeOperation(string input);
}
Run Code Online (Sandbox Code Playgroud)

然后实现此服务.最后控制器将使用它:

public class MyController: Controller
{
    private readonly IMyService _service;
    public class MyController(IMyService service)
    {
        _service = service;
    }

    public ActionResult Create(string input)
    {
        var model = _service.SomeOperation(input);
        var viewModel = Mapper.Map<DomainModel, ViewModel>(model);
        return View(viewModel);
    }
}
Run Code Online (Sandbox Code Playgroud)

并配置您的DI框架以将服务的正确实现传递到控制器.

备注:在我提供的示例中,我使用AutoMapper将域模型转换为传递给视图的视图模型.

  • 此代码具有AutoMapper依赖性,因此OP可能需要了解该引用 (2认同)

sta*_*k72 5

我在MVC项目中倾向于在我的操作之外保留尽可能多的业务逻辑,以便我可以测试它们

在某些情况下,我创建一个服务层,然后使用它

public class QuizRunner : IQuizRunner
{
    private readonly IServiceProxyclient _quizServiceProxy;
    public QuizRunner(IServiceProxyclient quizServiceProxy)
    {
        _quizServiceProxy = quizServiceProxy;
    }

    public GameCategory GetPrizeGameCategory(int prizeId)
    {
        return _quizServiceProxy.GetGameCategoryForPrizeId(prizeId);
    }

}

public interface IQuizRunner
{
    GameCategory GetPrizeGameCategory(int prizeId);
}



private IQuizRunner_serviceClass;

public AdminPowercontroller(IQuizRunner serviceClass)
{
    _serviceClass = serviceClass;
}


public ActionResult Create(string test1)
    var itemsFromLogic = _serviceClass.Method1();
    return View();
}
public ActionResult Index(string test1)
    var gameCategory = _serviceClass.GetPrizeGameCategory(test1);
    var viewModel = Mapper.Map<GameCategory, GameCategoryViewModel>(gameCategory);
    return View(viewModel);
}
Run Code Online (Sandbox Code Playgroud)

这允许我的操作与我的服务层分开测试,没有依赖性

希望这可以帮助

保罗