从Controller的胖方法创建一个Helper类

时间:2018-02-19 03:49:02

标签: asp.net-core

此方法接收从前端发布的CSV文件(Sale,Date),清理表并将csv文件记录插入表中,然后获取最新日期并将其返回到前端。我知道代码看起来有点难看,我有很多东西需要学习,但我想弄清楚的是如何从这段代码创建一个Helper类,因为这个方法太胖了我gess?

所以我尝试将一些代码迁移到Helper类然后我创建了一个静态类,但问题是我无法将依赖项注入到它的构造函数中,因为它是一个静态类...然后没有数据库服务来自帮助者类,这不是太“帮手”。

所以在您看来,这种方法太长/太胖了吗? 是否需要辅助班? 我该如何构建它?

干杯

这是我的控制器

private IDataService<Sale> _SaleDataService;
    private readonly MyOptions _myOptions;
    public DateTime LastWindowDay;
    public ForecastApiController(IDataService<Sale> service, IOptions<MyOptions> optionsAccessor)

    {
        _SaleDataService = service;
        _myOptions = optionsAccessor.Value;         
    }

[HttpPost("api/Sales/uploadFile")]
public async Task<IActionResult> UploadFiles()
{
    try
    {
        //clean table
        var all = _SaleDataService.GetAll();
        if (all.Count() > 0)
        {
            foreach (var item in all)
            {
                _SaleDataService.Delete(item);
            }
        }
        var files = Request.Form.Files;
        //Read Request for the unique uploaded file (method can process multiple but frontend will post just one)      
        foreach (var file in files)
        {
            using (System.IO.StreamReader sr = new StreamReader(file.OpenReadStream()))
            {
                //Reads the file one line at a time until its end
                String line = await sr.ReadLineAsync();
                while (sr.Peek() >= 0)
                {
                    //Split the values on the line and convert them into a propper format
                    var fileLine = sr.ReadLine();
                    var lineToArray = fileLine.Split(',').ToArray();
                    var timeElement = DateTime.Parse(lineToArray[0]);
                    var saleAmauntElement = float.Parse(lineToArray[1], System.Globalization.CultureInfo.InvariantCulture);
                    //Discard negative values and store data into database
                    if (saleAmauntElement >= 0)
                    {
                        //Store line into database
                        Sale sl = new Sale
                        {
                            SaleDate = timeElement,
                            SaleAmount = saleAmauntElement
                        };
                        _SaleDataService.Create(sl);
                        LastWindowDay = sl.SaleDate;
                    }
                }
                // Simple Moving Average method will be used and the restriction is that it will calculate only within a week after -
                // - last day of historical data.
                // Create an array and stores the next 7 days from the last day that there is data
                string[] predictionDays = new string[7];
                for (int i = 0; i < 7; i++)
                {
                    predictionDays[i] = LastWindowDay.AddDays(i + 1).ToString("dd/MM/yyyy");
                }
                //returns the array to frontend to let the user select a prediction day
                return Json(predictionDays);
            }
        }
        return Json(new { message = "Error trying to process information" });
    }
    catch (Exception ex)
    {
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return Json(new { message = ex.Message });
    }
}

1 个答案:

答案 0 :(得分:1)

遵循存储库模式有助于维护控制器和项目,这就像拥有一个包含所有操作(业务逻辑和数据库)的帮助程序类。

在你的Startup.cs

public interface IRepository
{

    IEnumerable<MyData> GetData();
}

创建界面

public partial class Repository : IRepository
{
    private DBContext _context;
    private ILogger<Repository> _logger;
    private IHttpContextAccessor _httpContextAccessor;

    public Repository(DBContext context, ILogger<Repository> logger, IHttpContextAccessor httpContextAccessor)
    {
        _context = context;
        _logger = logger;
        _httpContextAccessor = httpContextAccessor;

    }
    public async Task<bool> SaveChangesAsync()
    {
        return (await _context.SaveChangesAsync()) > 0;
    }
    public IEnumerable<MyData> GetData()
    {
        _logger.LogInformation("Getting All Data from the Database");
        return _context.Data.ToList();
    }
}

创建助手类

public class RequestsController : Controller
{
    private IRepository _repository;
    private ILogger<RequestsController> _logger;
    private IConfiguration _config;

    public RequestsController(IRepository repository,ILogger<RequestsController> logger,IConfiguration config)
    {

        _repository = repository;
        _logger = logger;
        _config = config;
    }

    // GET: Requests
    public IActionResult Index()
    {
        var data = _repository.GetData()
        return View(data);
    }
}

最后将其注入您的控制器

<?php
//some $data
$data[] = 1;
$data[] = 3;
$data[] = 2;
//read $config from file
if(file_exists('test.txt'))
{
$config = file('test.txt');
$config['state'] = $config[0];
unset($config[0]);
}
//catch REQUEST
if(isset($_REQUEST['state']))$config['state'] = $_REQUEST['state'];
//sort if request is 1
if($config['state'] == 1)
    sort($data);
//output $data
print_r($data);
//save config to file
file_put_contents('test.txt', implode(PHP_EOL, $config));