Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would AddScoped() behave outside Asp.net core?

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.

like image 788
VMh Avatar asked Aug 12 '17 18:08

VMh


People also ask

What is AddScoped in .NET Core?

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.

What is the difference between services AddScoped service Addtransient and services Addsingleton?

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.

Do transient services get disposed?

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.

Should services be scoped or Singleton?

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.


1 Answers

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)

like image 71
Tseng Avatar answered Oct 29 '22 04:10

Tseng