使用接口

时间:2017-12-17 10:36:25

标签: c# asp.net model-view-controller interface

我的服务中有这个方法,用于排序,过滤和分页:

        public async Task<IPagedList<VehicleMake>> GetVehicleMakesWithPaginationAsync(string search, int? page, string sort)
    {
        var makes = _context.VehicleMakes.AsQueryable();

        switch (sort)
        {
            case "Name desc":
                makes = makes.OrderByDescending(x => x.Name);
                break;
            default:
                makes = makes.OrderBy(x => x.Name);
                break;
        }

        return await makes.Where(x => x.Name.StartsWith(search) || search == null).ToPagedListAsync(page ?? 1, 5);
    }

此方法从控制器操作方法接收它的参数:

        public async Task<ActionResult> Index(string search, int? page, string sort)
    {
        ViewBag.SortNameParameter = string.IsNullOrEmpty(sort) ? "Name desc" : "";

        return View(await _vehicleMakeService.GetVehicleMakesWithPaginationAsync(search, page, sort));
    }

我被告知我应该将这些参数提取到带有接口的单独类中,例如:

public interface IFiltering
{
  string Search { get; set; }
}

public class Filtering: IFiltering
{
   public string Search { get; set; }
}

然后在我的方法中做出改变:

Task<IPagedList<VehicleMake>> GetVehicleMakesWithPaginationAsync(string search, int? page, string sort)

到此:

Task<IPagedList<VehicleMake>> GetVehicleMakesWithPaginationAsync(IFiltering filtering, int? page, string sort)

我不知道该怎么做。如果我这样做,我的控制器操作方法中出现错误“无法从字符串转换为IFiltering”。如果我也将控制器动作方法中的参数更改为IFiltering,我会收到错误“无法创建接口实例”。我应该使用依赖注入吗?以哪种方式?

0 个答案:

没有答案