Reputation:
I was reading a book which says:
When the application starts, ASP.NET Core creates a new instance of the
Startup
class and calls itsConfigureServices
method so that the application can create its services and services are objects that provide functionality to other parts of the application
I'm a little bit confused, because it looks like a service/object is created before it is actually needed in a Controller.
Let's say there is only a Controller that required an UptimeService
object and CalculateController
(not default mapping controller) is the only controller that needs an UptimeService
object, so I add:
//Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<UptimeService>();
services.AddMvc();
}
Let's say we run the application with routing to Home/Index
first, my questions are:
According to the picture above, an UptimeService
is always created, even we don't go to Calculate/Index
and because CalculateController
is the only controller that needs an UptimeService
, isn't it very inefficient?
I often hear 'register a service', is it the same thing as 'create a service'?
Upvotes: 2
Views: 528
Reputation: 1620
Q2. No, registering a service does not mean creating a service.
Registering a services only configures the IoC Container for dependency injection. It means that services.AddSingleton<UptimeService>();
will not create an instance of UptimeService
, it will only "configure" the IoC container so that it can provide you an instance of UptimeService
when you ask for it.
Q1. Now that you know that "registering a service" and "creating a service" are two different things, in the Startup
class you only register services therefore, instance of UptimeService
will only be created when the controller which has dependency on UptimeService
is created, and that controller will only be created when you make a HTTP request that routes to that controller.
Controllers are created on every request, but since you are adding your service as Singleton
, the same instance of this service will be provided to the controllers, but new instance of the controller will be created on every request.
Upvotes: 1