text
stringlengths
0
13.4k
Use dependency injection
TodoController class, in this case). By adding an ITodoItemService
parameter to the constructor, you've declared that in order to create the
TodoController , you'll need to provide an object that matches the
ITodoItemService interface.
Interfaces are awesome because they help decouple (separate) the
logic of your application. Since the controller depends on the
ITodoItemService interface, and not on any specific class, it
doesn't know or care which class it's actually given. It could be the
FakeTodoItemService , a different one that talks to a live database,
or something else! As long as it matches the interface, the
controller can use it. This makes it really easy to test parts of your
application separately. I'll cover testing in detail in the Automated
testing chapter.
Now you can finally use the ITodoItemService (via the private variable
you declared) in your action method to get to-do items from the service
layer:
public IActionResult Index()
{
var items = await _todoItemService.GetIncompleteItemsAsync();
// ...
}
Remember that the GetIncompleteItemsAsync method returned a
Task<TodoItem[]> ? Returning a Task means that the method won't
necessarily have a result right away, but you can use the await keyword
to make sure your code waits until the result is ready before continuing
on.
The Task pattern is common when your code calls out to a database or
an API service, because it won't be able to return a real result until the
database (or network) responds. If you've used promises or callbacks in
37
Use dependency injection
JavaScript or other languages, Task is the same idea: the promise that
there will be a result - sometime in the future.
If you've had to deal with "callback hell" in older JavaScript code,
you're in luck. Dealing with asynchronous code in .NET is much
easier thanks to the magic of the await keyword! await lets
your code pause on an async operation, and then pick up where it
left off when the underlying database or network request finishes.
In the meantime, your application isn't blocked, because it can
process other requests as needed. This pattern is simple but takes
a little getting used to, so don't worry if this doesn't make sense
right away. Just keep following along!
The only catch is that you need to update the Index method signature
to return a Task<IActionResult> instead of just IActionResult , and
mark it as async :
public async Task<IActionResult> Index()
{
var items = await _todoItemService.GetIncompleteItemsAsync();
// Put items into a model