Learn

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

1.

We’ve provided another service called IStringGenerator with an implementation called SuperpowerGenerator. Register it in Startup.cs as a singleton.

2.

Access the IStringGenerator service in IndexModel.cshtml.cs:

  • Declare a private readonly field of type IStringGenerator.
  • Add an IStringGenerator parameter to the constructor.
  • In the constructor body, store the parameter’s value in your new field.
3.

Use the IStringGenerator service in the page model:

  • In OnGet(), call the IStringGenerator field’s Generate() method and store the returned value in Superpower.

Sign up to start coding

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?