How to select the lifetime scope for dependencies

Newbie Dev 151 Reputation points
2021-12-22T11:56:45.93+00:00

Hi,
I am following the example in the link below,

https://github.com/microsoftgraph/msgraph-training-changenotifications/blob/master/demos/03-track-changes/Controllers/NotificationsController.cs

If I move the methods in it to separate service classes, what should be the scope while registering services in Startup.cs

For example if I move the Graph related methods(GetGraphClient(),GetAccessToken() etc) to GraphService and create an interface IGraphService , how should I register it in startup? Soped?transient?singleton?

Thanks

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,208 questions
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,715 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Jaliya Udagedara 2,736 Reputation points MVP
    2021-12-22T18:58:51.8+00:00

    It's important to understand the lifetime of the services when you are doing the DI, so you can choose what's best.

    • services.AddTransient:<>
      • Transient objects are always different. That's a new object is created every time it's requested.
    • services.AddScoped<>
      • Scoped objects are the same for a given request but differ across each new request.
    • services.AddSingleton<>
      • Singleton objects are the same for every request.

    I believe this will help you determine what's best for your scenario.

    1 person found this answer helpful.

  2. AgaveJoe 26,146 Reputation points
    2022-01-09T18:44:25.437+00:00

    The documentation is very clear and states, "Singleton objects are the same for every request." It does not matter what device, user (browser), client makes the request, the Singleton is the same instance for every request.

    Dependency Injection: Lifetime and registration options

    I believe scoped dependency is alive for the session of the user.

    No. Scoped life time is the duration of a request. A new request gets a new scope. From the docs... "Scoped objects are the same for a given request but differ across each new request."

    Is there any convention that service class should be scoped, repository class should be singleton etc?

    It depends on the repository design.

    1 person found this answer helpful.
    0 comments No comments