Understanding dependency lifetimes
If you're completely new to ASP.NET Core, or haven't worked with ASP.NET Core for a long time, or if you're an experienced ASP.NET developer but don't really look into dependency lifetimes in detail, the chances are you might be using just one type of dependency lifetime to register all your services when building ASP.NET Core applications. This is because you are confused as to which service lifetime to use, and you wanted to play it safe. Well, that's understandable, because choosing which type of service lifetime to use can be confusing sometimes. Hopefully, this section will give you a better understanding of the different types of lifetimes that you can use within your application and decide when to use each option.
There are primarily three service lifetimes in ASP.NET Core DI:
- Transient
- Scoped
- Singleton
Transient service
The AddTransient()
method is probably what you were using most often...