Search code examples
c#asp.net-core.net-corebackground-servicetransient

Transient BackgroundService, the instance that is returned is always different?


So I have a scenario where i have to execute several tasks in parallel, i have a class with a generic type that inherits from a BackgroundService, that will be responsible for executing a single task. For each task i want a new instance to perform the given task. The goal is to have a pool of workers.

Worker<T>:BackgroundService

In the startup I add it as follows:

services.AddTransient(typeof(Worker<>));

My question is, when i ask the ServiceProvider for a new instance, the instance that is returned is always different?


Solution

  • My question is, when i ask the ServiceProvider for a new instance, the instance that is returned is always different?

    Yes, that's the point of being "transient". "Scoped" returns same instance within the scope (in ASP.NET Core during one request) and "Singleton" is same instance always.

    However, if your transient service has scoped dependencies, these may not always be same (depending if you resolve inside the scope or not). You should avoid having scoped dependencies for transient services.

    If you have scoped services and you can't have them transient, you gotta create a scope. That could happen by spinning a task, resolving the IServiceScopeFactory, resolving the services you need, call them, then dispose the scope (which dispose all of its scoped and transient dependencies)

    var scopeFactory = _serviceProvider.GetService<IServiceScopeFactory>()
    using(var scope = scopeFactory.CreateScope())
    {
         var myService = scope.ServiceProvider.GetRequiredService<Worker<MyT>>();
    }