Member-only story
How to Choose Between AddTransient and AddScoped for Repository Registration in ASP.NET Core: A Comprehensive Guide
When building applications with ASP.NET Core, it’s common to use dependency injection to manage dependencies between different components. One aspect of this is registering repository classes that handle interactions with a database or other data store.
When registering a repository with the ASP.NET Core dependency injection container, there are two options for the lifetime of the repository: transient and scoped. Here’s what you need to know about the difference between the two.
Transient Repositories
A transient repository is created every time it’s needed, and then disposed of once the operation that requested it has been completed. This means that a new instance of the repository is created every time it’s requested.
Here’s an example:
services.AddTransient<IRepository, Repository>();
In this example, a new instance of Repository
will be created every time it's requested.
This might be appropriate for certain types of repositories, such as those that handle read-only operations, or those that are very lightweight.