wasAsked.

Which DI lifetime would you choose for a logging service and an email service?

PwC · Role not specified · technical

Published

Asked in 2026 · .NET

Community answers

Posted by wasAsked editorial collection

Start from what each service holds and whether it is thread-safe. Logging service - If you use the built-in ILogger<T>, you do not register anything yourself: the logging infrastructure registers ILoggerFactory and ILogger<T> as singletons, and they are thread-safe. - For a custom logging or audit wrapper that is stateless and thread-safe, singleton is appropriate — it is used everywhere and has no per-request state. - Exception: if the logger needs per-request data (current user, tenant, correlation ID), either make it scoped or, better, keep it singleton and add context through logging scopes (logger.BeginScope) or enrichers. Email service - An email sender usually depends on configuration (singleton-friendly), an HTTP client or SMTP client, and sometimes request-specific information or a DbContext (for templates or an outbox). - If it is stateless and uses IHttpClientFactory or a provider SDK client that is thread-safe (for example the SendGrid client), singleton or transient both work. Many teams choose transient or scoped for simplicity and safety. - If it depends on DbContext (for example writing to an outbox table), it must be scoped. - Avoid creating a new SmtpClient per call without disposal; also note Microsoft recommends MailKit over System.Net.Mail.SmtpClient for new code. Example answer: "I would rely on the built-in ILogger<T>, which is a singleton. For email I would register IEmailSender as scoped, because in our app it writes to an outbox table through DbContext and a background worker sends the email. If it only called an HTTP API through IHttpClientFactory, I could make it transient or singleton." Bonus point: sending email inside the request is risky — slow SMTP servers increase latency and failures lose messages. Queue emails (outbox plus background service) and make sending retryable and idempotent.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics