我应该在哪里把我的控制器业务逻辑MVC3 [英] Where should I put my controller business logic in MVC3

查看:125
本文介绍了我应该在哪里把我的控制器业务逻辑MVC3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解MVC是所有关于把事情在正确的地方,它应该是逻辑。我的控制器动作也越来越充满了业务逻辑(不涉及数据存储),我觉得我应该开始将一些逻辑到不同的地方。

有没有在那里我应该把这个逻辑的约定?比如我有以下控制器的位于控制器文件:

  adminPowerController  公众的ActionResult创建(字符串TEST1)
    //业务逻辑
    //业务逻辑
    //业务逻辑
    返回查看();
  }
  公众的ActionResult指数(字符串TEST1)
    //业务逻辑
    //业务逻辑
    //业务逻辑
    返回查看();
  }


解决方案

把业务逻辑推荐的地方是成一个服务层。所以,你可以定义一个接口,这将重新present业务运作:

 公共接口IMyService
{
    的DomainModel SomeOperation(字符串输入);
}

和然后让该服务的实现。最后,控制器将使用它:

 公共类myController的:控制器
{
    私人只读IMyService _service;
    公共类myController的(IMyService服务)
    {
        _Service =服务;
    }    公众的ActionResult创建(字符串输入)
    {
        VAR模型= _service.SomeOperation(输入);
        VAR视图模型= Mapper.Map<的DomainModel,视图模型>(模型);
        返回视图(视图模型);
    }
}

和配置DI框架,服务的正确执行传递到控制器。

备注:在这个例子中我提供了我所用 AutoMapper 以领域模型之间的转换成传递一个视图模型到视图。

I understand MVC is all about putting things in the correct place and the logic where it should be. My controller actions are getting filled up with business logic (not related to data storage) and I feel that I should start moving some of the logic to a different place.

Is there a convention for where I should place this logic? For example I have the following controller that's located in the controllers file:

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();
  }

解决方案

The recommended place to put business logic is into a service layer. So you could define an interface which will represent the business operation:

public interface IMyService
{
    DomainModel SomeOperation(string input);
}

and then have an implementation of this service. Finally the controller will use it:

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);
    }
}

and configure your DI framework to pass the proper implementation of the service into the controller.

Remark: In the example I provided I used AutoMapper to convert between a domain model into a view model which is passed to the view.

这篇关于我应该在哪里把我的控制器业务逻辑MVC3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆