Let's say I want to use dependency injection in a console application that would run as an Azure web job. Doing so I am reusing my custom service registration method called "AddATonOfServices()" which I use on a related Asp.net application.
My question is, how would the services that are registered in "AddATonOfServices()" using AddScoped() behave now in the console App? are they behaving like Transient or Singleton, or HOW? Would there be any unexpected behavior?
Thanks.
AddScoped() - This method creates a Scoped service. A new instance of a Scoped service is created once per request within the scope. For example, in a web application it creates 1 instance per each http request but uses the same instance in the other calls within that same web request.
With a scoped service we get the same instance within the scope of a given http request but a new instance across different http requests. With Singleton service, there is only a single instance.
Disposable transient services are captured by the container for disposal. This can turn into a memory leak if resolved from the top-level container. Enable scope validation to make sure the app doesn't have singletons that capture scoped services.
Scoped services service is the better option when you want to maintain state within a request. Singletons are created only once and not destroyed until the end of the Application. Any memory leaks in these services will build up over time.
It will be resolved as scoped, if you create a scope via IServiceScopeFactory
.
// provider is the root container
using(var scope = provider.GetService<IServiceScopeFactory>().CreateScope())
{
var scopedService = scope.ServiceProvider.GetRequiredService<IScopedService>();
// do something
}
// scope will be disposed and all scoped and transient services which implement IDisposable
If you resolve a scoped service from the root container, then it will be effectively a singleton (assuming provider
lives as long as the application does)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With