wasAsked.

If you have a calculation service, should it be Transient or Scoped, and why?

Impetus · Role not specified · technical

Published

Year not specified · Software Engineering

Community answers

Posted by wasAsked editorial collection

For a typical calculation service, I would choose transient (or even singleton) — not scoped — because a calculation service is usually stateless. Reasoning - A pure calculation service (tax, discount, EMI or pricing formulas) takes inputs and returns outputs without storing data between calls. - Stateless services are safe with any lifetime, so pick based on cost and dependencies: - Transient: a fresh lightweight instance each time; simple and safe. The cost of creating a small object is negligible. - Singleton: if the service is stateless and thread-safe, one shared instance avoids allocations entirely; a good choice for frequently used pure logic. - Scoped is meant for services that hold per-request state or depend on scoped services such as DbContext. A pure calculator has no reason to be scoped. When the answer changes - It depends on DbContext or another scoped service (for example it reads tax rates from the database): it must be scoped (or transient resolved within a scope). A singleton would capture the scoped DbContext — a captive dependency bug. - It holds per-request state (caches intermediate results for the current request): scoped. - It holds mutable state that should not be shared: transient, never singleton. - It loads expensive configuration (rate tables) once: singleton with thread-safe, read-only data — or separate the rate loading (singleton cache) from the calculation. Example public sealed class EmiCalculator : IEmiCalculator { public decimal MonthlyPayment(decimal principal, decimal annualRate, int months) { var r = annualRate / 12 / 100; if (r == 0) return principal / months; var factor = (decimal)Math.Pow((double)(1 + r), months); return principal * r * factor / (factor - 1); } } builder.Services.AddSingleton<IEmiCalculator, EmiCalculator>(); // stateless and thread-safe // or AddTransient — both are correct; scoped adds no benefit here Interview summary: "Lifetime follows state and dependencies. A stateless calculation service can be transient or singleton; I would use singleton if it is thread-safe and heavily used, transient otherwise. I would only make it scoped if it depended on scoped services like DbContext."

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics