In the past exercise, we registered a service with the method AddScoped()
. Each service has a “lifetime” and we wanted our service to have a lifetime “scoped to each user”. This lesson won’t get too deep into the details; you just need to know that there are three lifetime options:
AddScoped<T1, T2>()
- the service class is instantiated once per user, across the web app.AddTransient<T1, T2>()
- the service class is instantiated every time it is requested.AddSingleton<T1, T2>()
- the service class is instantiated once. That object is used throughout the web app, and across users.
In general, you use them like so:
public void ConfigureServices(IServiceProvider services) { services.AddScoped<IAccount, CustomerAccount>(); services.AddTransient<IResponder, Responder>(); services.AddSingleton<ILogger, Logger>(); }
By the way, when we say “register” we mean “register an abstraction and its implementation with the IoC Container so that other classes can access the implementation via dependency injection”.
Instructions
We’ve provided another service called IStringGenerator
with an implementation called SuperpowerGenerator
. Register it in Startup.cs as a singleton.
Access the IStringGenerator
service in IndexModel.cshtml.cs:
- Declare a
private
readonly
field of typeIStringGenerator
. - Add an
IStringGenerator
parameter to the constructor. - In the constructor body, store the parameter’s value in your new field.
Use the IStringGenerator
service in the page model:
- In
OnGet()
, call theIStringGenerator
field’sGenerate()
method and store the returned value inSuperpower
.