如何在 API 和普通控制器中重用查询?
通过不在 API 或 MVC 控制器中定义查询。您可以在 MVC 项目外部的共享程序集中定义查询,并让控制器调用该层。
例子:
外化
public interface IQuery<TResult> {}
public interface IQueryProcessor
{
TResult Execute<TResult>(IQuery<TResult> query)
}
public class MyQueryObject : IQuery<MyEntity[]>
{
public string QueryParam1 { get; set; }
public int QueryParam2 { get; set; }
}
API 控制器
public class MyApiController : ApiController
{
private readonly IQueryProcessor _queryProcessor;
public MyApiController(IQueryProcessor queryProcessor)
{
_queryProcessor = queryProcessor
}
public IEnumerable<MyApiModel> Get
([FromUri] string queryParam1, int queryParam2)
{
var query = new MyQueryObject
{
QueryParam1 = queryParam1,
QueryParam2 = queryParam2,
};
var results = _queryProcessor.Execute(query);
return Mapper.Map<IEnumerable<MyApiModel>>(results);
}
}
MVC 控制器
public class MyMvcController : Controller
{
private readonly IQueryProcessor _queryProcessor;
public MyMvcController(IQueryProcessor queryProcessor)
{
_queryProcessor = queryProcessor
}
public ViewResult Index(string queryParam1, int queryParam2)
{
var query = new MyQueryObject
{
QueryParam1 = queryParam1,
QueryParam2 = queryParam2,
};
var results = _queryProcessor.Execute(query);
var models = Mapper.Map<IEnumerable<MyViewModel>>(results);
return View(models);
}
}