text
stringlengths 0
13.4k
|
|---|
// Pass the view to a model and render
|
}
|
You're almost there! You've made the TodoController depend on the
|
ITodoItemService interface, but you haven't yet told ASP.NET Core that
|
you want the FakeTodoItemService to be the actual service that's used
|
under the hood. It might seem obvious right now since you only have
|
one class that implements ITodoItemService , but later you'll have
|
multiple classes that implement the same interface, so being explicit is
|
necessary.
|
38
|
Use dependency injection
|
Declaring (or "wiring up") which concrete class to use for each interface
|
is done in the ConfigureServices method of the Startup class. Right
|
now, it looks something like this:
|
Startup.cs
|
public void ConfigureServices(IServiceCollection services)
|
{
|
// (... some code)
|
services.AddMvc();
|
}
|
The job of the ConfigureServices method is adding things to the service
|
container, or the collection of services that ASP.NET Core knows about.
|
The services.AddMvc line adds the services that the internal ASP.NET
|
Core systems need (as an experiment, try commenting out this line). Any
|
other services you want to use in your application must be added to the
|
service container here in ConfigureServices .
|
Add the following line anywhere inside the ConfigureServices method:
|
services.AddSingleton<ITodoItemService, FakeTodoItemService>();
|
This line tells ASP.NET Core to use the FakeTodoItemService whenever
|
the ITodoItemService interface is requested in a constructor (or
|
anywhere else).
|
AddSingleton adds your service to the service container as a singleton.
|
This means that only one copy of the FakeTodoItemService is created,
|
and it's reused whenever the service is requested. Later, when you write
|
a different service class that talks to a database, you'll use a different
|
approach (called scoped) instead. I'll explain why in the Use a database
|
chapter.
|
39
|
Use dependency injection
|
That's it! When a request comes in and is routed to the TodoController ,
|
ASP.NET Core will look at the available services and automatically supply
|
the FakeTodoItemService when the controller asks for an
|
ITodoItemService . Because the services are "injected" from the service
|
container, this pattern is called dependency injection.
|
40
|
Finish the controller
|
Finish the controller
|
The last step is to finish the controller code. The controller now has a list
|
of to-do items from the service layer, and it needs to put those items into
|
a TodoViewModel and bind that model to the view you created earlier:
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.