public Interface IStackoverflowService
{
IEnumerable<Question> GetRecentQuestions();
void PostAnswer(Question question, Answer answer);
}
public class StackoverflowService : IStackoverflowService
{
private StackoverflowDbContext _container;
public StackoverflowService(StackoverflowDbContext container)
{
_container = container;
}
public IEnumerable<Question> GetRecentQuestions()
{
var model = _container.Questions.OrderByDescending(x => x.Posted);
return model.Take(20);
}
public void PostAnswer(Question question, Answer answer) { ... }
}
然后在您的控制器中:
public class HomeController : Controller
{
private IStackoverflowService _stackoverflowService;
public HomeController(IStackoverflowService stackoverflowService)
{
_stackoverflowService = stackoverflowService;
}
public ActionResult Index()
{
var model = _stackoverflowService.GetRecentQuestions();
return View(model);
}
}
One solution is to use a service layer to handle this for you:
public Interface IStackoverflowService
{
IEnumerable<Question> GetRecentQuestions();
void PostAnswer(Question question, Answer answer);
}
public class StackoverflowService : IStackoverflowService
{
private StackoverflowDbContext _container;
public StackoverflowService(StackoverflowDbContext container)
{
_container = container;
}
public IEnumerable<Question> GetRecentQuestions()
{
var model = _container.Questions.OrderByDescending(x => x.Posted);
return model.Take(20);
}
public void PostAnswer(Question question, Answer answer) { ... }
}
Then in your controller:
public class HomeController : Controller
{
private IStackoverflowService _stackoverflowService;
public HomeController(IStackoverflowService stackoverflowService)
{
_stackoverflowService = stackoverflowService;
}
public ActionResult Index()
{
var model = _stackoverflowService.GetRecentQuestions();
return View(model);
}
}
You can even break it out into multiple services such as a QuestionsService, an AnswersService, a UsersService, etc.
发布评论
评论(1)
一种解决方案是使用服务层来为您处理这个问题:
然后在您的控制器中:
您甚至可以将其分解为多个服务,例如
QuestionsService
、AnswersService
,UsersService
等。One solution is to use a service layer to handle this for you:
Then in your controller:
You can even break it out into multiple services such as a
QuestionsService
, anAnswersService
, aUsersService
, etc.