Azure / durabletask

Durable Task Framework allows users to write long running persistent workflows in C# using the async/await capabilities.
Apache License 2.0
1.47k stars 287 forks source link

What is the recommendation from DTF on Dependency Injection on ServiceCollection - to use AddTransient or to use AddScoped for Orchestrations/Activities? #1082

Closed Pr1yanka closed 2 months ago

Pr1yanka commented 2 months ago

We are currently implementing a use case using DTF where we are using ObjectCreator to initialize orchestrations and activities with dependency injection. We read that AddTransient could be a problem while registering orchestrations/activities [here](https://stackoverflow.com/questions/43244316/iserviceprovider-garbage-collection-disposal#:~:text=15,ServiceProvider.GetRequiredService%3CIDataContext%3E())%0A%7B%20...%20%7D):

What we are currently doing is this?

 ServiceCollection collection = new ServiceCollection();
 collection.AddTransient<Orchestrator1>();
 collection.AddTransient<Activity1>();
//code to create invoke ObjectCreators

Should this be changed to below instead?

 collection.AddScoped<Orchestrator1>();
 collection.AddScoped<Activity1>();

Most examples and [blogs](https://andrewstevens.dev/posts/dependency-injection-durable-task/#:~:text=Make%20sure%20to%20use%20the%20Transient%20lifetime%20so%20that%20Durable%20Task%20Framework%20can%20get%20a%20new%20instance%20each%20time%20it%20calls%20Create()%20on%20the%20ObjectCreator.) suggest using transient but is there an official guidance on this?

@cgillum any recommendations?

jviau commented 2 months ago

There is no single answer to this. Your business logic of the individual classes will be the deciding factor - we cannot tell you what to do as we do not know your classes.

I will say that the stackoverflow link is not entirely accurate - there is nuance to what the service container disposes. Here is some documentation on this: https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-guidelines#disposal-of-services

Closing as this question is not something we (as the Durable Framework) can answer.