wasAsked.

Can we register the same file with different service lifetime?

Agiliad Technologies Pvt Ltd · Role not specified · technical

Published

Asked in 2026 · Software Engineering

Community answers

Posted by wasAsked editorial collection

"The same file" here usually means the same class or service type. The answer is yes, technically — but you should understand exactly what happens, because it often causes bugs. Registering the same interface twice builder.Services.AddSingleton<INotifier, EmailNotifier>(); builder.Services.AddScoped<INotifier, EmailNotifier>(); - The container keeps both registrations. - Resolving INotifier (constructor injection or GetService) returns the last registration — here, the scoped one. - Resolving IEnumerable<INotifier> returns both instances, each with its own lifetime (one singleton, one scoped). This is rarely intentional and confusing to readers. Registering one class under different service types with different lifetimes builder.Services.AddSingleton<ICache, MemoryCacheService>(); builder.Services.AddScoped<MemoryCacheService>(); Each registration creates its own instances: the ICache singleton and the scoped MemoryCacheService are different objects. If the class holds state, consumers see different state depending on which type they requested — a subtle bug. Sharing one instance across several interfaces (a common legitimate need) builder.Services.AddSingleton<OrderCache>(); builder.Services.AddSingleton<IOrderReader>(sp => sp.GetRequiredService<OrderCache>()); builder.Services.AddSingleton<IOrderWriter>(sp => sp.GetRequiredService<OrderCache>()); Now all three resolve to the same singleton instance. Keep the lifetimes consistent; forwarding a singleton interface to a scoped implementation would create a captive dependency. Keyed services (.NET 8+) If you deliberately need different configurations of the same type: builder.Services.AddKeyedSingleton<IStorage, BlobStorage>("archive"); builder.Services.AddKeyedScoped<IStorage, BlobStorage>("uploads"); // consume with [FromKeyedServices("archive")] IStorage storage Avoiding accidental duplicates - Libraries use TryAddSingleton, TryAddScoped and TryAddEnumerable, which register only if no registration exists, so they do not override application choices. - Validate the container with ValidateOnBuild and ValidateScopes to catch lifetime problems. Summary answer: "Yes, the container allows it — the last registration wins for single resolution and all are returned for IEnumerable — but mixing lifetimes for the same type is usually a mistake. If I need one instance behind several interfaces, I forward the registrations to a single registration with one lifetime."

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics