您确实应该避免使用胖控制器。但一如既往说起来容易做起来难。
所以让我试着用一个例子来回答你的问题。与往常一样,您将首先设计一个视图模型,该模型将代表用户发送给此操作的数据(不要使用任何弱类型FormCollection
或ViewData
)
public class UploadViewModel
{
[Required]
public HttpPostedFileBase File { get; set; }
}
然后我们转到控制器:
public ProductsController: Controller
{
private readonly IProductsService _service;
public ProductsController(IProductsService service)
{
_service = service;
}
public ActionResult Upload()
{
var model = new UploadViewModel();
return View(model);
}
[HttpPost]
public ActionResult Upload(UploadViewModel model)
{
if (!ModelState.IsValid)
{
// The model was not valid => redisplay the form
// so that the user can fix his errors
return View(model);
}
// at this stage we know that the model passed UI validation
// so let's hand it to the service layer by constructing a
// business model
string error;
if (!_service.TryProcessFile(model.File.InputStream, out error))
{
// there was an error while processing the file =>
// redisplay the view and inform the user
ModelState.AddModelError("file", error);
return View(model);
}
return Content("thanks for submitting", "text/plain");
}
}
最后一位是服务层。它将有 2 个依赖项:第一个负责解析输入流并返回Product
s 列表,第二个负责将这些产品持久化到数据库中。
像这样:
public class ProductsService: IProductsService
{
private readonly IProductsParser _productsParser;
private readonly IProductsRepository _productsRepository;
public ProductsService(IProductsParser productsParser, IProductsRepository productsRepository)
{
_productsParser = productsParser;
_productsRepository = productsRepository;
}
public bool TryProcessFile(Stream input, out string error)
{
error = "";
try
{
// Parse the Excel file to extract products
IEnumerable<Product> products = _productsParser.Parse(input);
// TODO: Here you may validate whether the products that were
// extracted from the Excel file correspond to your business
// requirements and return false if not
// At this stage we have validated the products => let's persist them
_productsRepository.Save(products);
return true;
}
catch (Exception ex)
{
error = ex.Message;
}
return false;
}
}
那么当然你会有这些依赖的两个实现:
public class ExcelProductsParser: IProductsParser
{
public IEnumerable<Product> Parse(Stream input)
{
// parse the Excel file and return a list of products
// that you might have extracted from it
...
}
}
和存储库:
public class Linq2SqlProductsRepository: IProductsRepository
{
public void Save(IEnumerable<Product> products)
{
// save the products to the database
...
}
}
备注:您可以使用其他属性来丰富视图模型,这些属性将表示我们可以与此文件上传相关联的一些元数据,并且可能在表单上有一些相应的输入字段。然后,您可以定义一个业务模型来传递给该TryProcessFile
方法,而不是简单的Stream
. 在这种情况下,可以在控制器操作中使用AutoMapperUploadViewModel
在您定义的新业务模型和新业务模型之间进行映射。