1

I'm wondering... why does Microsoft use this:

 services.AddTransient<IEmailSender, AuthMessageSender>();

In their tutorials for sending e-mails in ASP.NET Core rather than:

 services.AddSingleton<IEmailSender, AuthMessageSender>();

Isn't the service supposed to stay the same for the lifetime of the project? What is the downside of this?

Thanks :)

Techy
  • 2,026
  • 4
  • 20
  • 41
  • If you can guarantee the service is thread-safe, then sure make it a singleton. Otherwise, best be safe. As for why Microsoft chose, this, you'll have to ask them. – DavidG Mar 01 '17 at 17:25
  • @DavidG can you please explain more about thread safe, what I have done is an HttpClient that gets initialized once then it is called upon sending e-mails as PostAsync... what do you think? – Techy Mar 01 '17 at 17:33
  • 1
    [What is meant by “thread-safe” code?](http://stackoverflow.com/questions/261683/what-is-meant-by-thread-safe-code) – DavidG Mar 01 '17 at 17:35

1 Answers1

1

The reason why they use Transient its because their example is based on Forgot Password.

Forgot password is something secundary it doesnt do part of the main app logic, so it is cheaper in terms of resources to create the service once you need it and after use, discard it. This is the reason they use Transient.

If its a singleton it will be always in memory once it is created and for the forgot passward case which is rare to happens, it is not worth it.

MarchalPT
  • 1,268
  • 9
  • 28