0

I have tried to use DogStatsdService as a singleton object, but it seems that you need to call Flush so metrics are sent.

I have tried to register DogStatsdService as a scoped dependency, and it seems to work fine and custom metrics are sent in each request, however... is this the right way of using that service?

vtscop
  • 31
  • 11

1 Answers1

0

You would need to understand how the service behaves in your program and choose an appropriate lifetime for it.

Singleton which creates a single instance throughout the application. It creates the instance for the first time and reuses the same object in the all calls.

Scoped lifetime services are created once per request within the scope. It is equivalent to a singleton in the current scope. For example, in MVC it creates one instance for each HTTP request, but it uses the same instance in the other calls within the same web request.

Transient lifetime services are created each time they are requested. This lifetime works best for lightweight, stateless services.

This example from .NET documentation shows the difference.

For more details, you can refer to akardon's answer for a better understanding of the three main lifecycles of dependency injection in .net core.

Chen
  • 4,499
  • 1
  • 2
  • 9