2

I recently run upon a net core project with the current configuration:

services.AddTransient<Service1>();
services.AddSingleton<Service1>();

Where Service1 was a class. What could possibly be the purpose of this? Or its just a mistake? Is there any way to choose whether to use a new instance of the service or the singleton dynamically?

kkica
  • 4,034
  • 1
  • 20
  • 40

1 Answers1

2

The last registration "wins" so your Service1 type will be registered as a singleton given your current code.

If you change the order of the calls, it's going to be registered as a transient dependency. But don't do both. Choose one lifetime per type.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • 1
    adding to the above, if you use TryAdd instead of Add, it will keep the first registration https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.extensions.servicecollectiondescriptorextensions.tryadd?view=dotnet-plat-ext-3.1 – Jonathan Busuttil Feb 24 '20 at 10:56