2.4: Registering Auth Service
We need to make our AuthService.cs class injectable into other parts of our application.
Open up the Startup class in the .API project.
Remember the ConfigureServices() method? This is where we register services for dependency injection.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<EFConnectContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
services.AddScoped<IAuthService, AuthService>(); // registering our AuthService
}The formula is:
service.[Lifetime]<[interface], [concrete]>();
Transient vs. Singleton vs. Scoped
What is the AddScoped() method?
There are three different "lifetimes" we have to choose from for dependency injection.
Transient - each time the service is requested, a new instance of our service is created.
Scoped - one instance of our service is created for each web request.
Singleton - one instance of our service is created for the entire lifetime of our application. After initial request is made - all additional requests will use the same instance.
These are a bit confusing, but they will make more sense as we use them.
Note: built-in methods like AddDbContext() and AddMvc() handle it for us. This is just for custom services we want to inject.
Last updated