Dependency injection interview questions
Service lifetimes, constructor injection, captive dependencies.
4 questions with answers and explanations · 2 flashcards
Key ideas
- Register services on
builder.Services; ask for them through constructor injection. - Lifetimes: Transient (new every resolve), Scoped (one per request/scope), Singleton (one for the app).
- A longer-lived service must not hold a shorter-lived one (captive dependency), e.g. a singleton holding a scoped
DbContext. - Singletons that need scoped services should create a scope with
IServiceScopeFactory.
Questions
- Which service lifetime gives one instance per HTTP request in ASP.NET Core?Multiple choiceEasy
- A teammate describes their service registrations. Highlight the statements that describe a lifetime bug.Highlight textHard
- Why use dependency injection? Explain constructor injection and the benefits it brings to an ASP.NET Core app.Interview answerMedium
- Complete the registration so a new instance is created every time IFoo is resolved: builder.Services.Add_____<IFoo, Foo>();Fill in the blankEasy