1

I am trying to understand how the Dependency Injection service registry works. I have a generic repository that does database operations for any table such as GetAll(), GetById() ... and another service that will commit to the database. such as Save(); Commit();

I have read AddTransient, AddScoped and AddSingleton Services Differences?

My question is what would be the best option to register the Generic Repository service and Db service and why?

services.AddScoped (typeof (IRepository<>), typeof (Repository<>));
services.AddTransient (typeof (IRepository<>), typeof (Repository<>));
services.AddSingleton (typeof (IRepository<>), typeof (Repository<>));
0

1 Answer 1

3

Use AddScoped . Scoped services are created per scope. In a web application, every web request creates a new separated service scope. That means scoped services are generally created per web request.

If you're calling db multiple times in the same request, then use scoped lifetime will help keeping the same repository object in the memory and reuses that multiple times within the same Http Request context. If using transient , it will creates a new repository object multiple times and consumes more memory .

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.