0

When adding AWS Services to Services Collection in .NET Core, should I go with the default which well add as a Singleton or should I use the override to set as Transient?

For reference, displaying default option (Singleton) for DynamoDB and Transient for SQS:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddDefaultAWSOptions(Configuration.GetAWSOptions());
        services.AddHttpContextAccessor();

        // Add AWS Services
        services.AddDefaultAWSOptions(Configuration.GetAWSOptions());
        services.AddAWSService<IAmazonDynamoDB>();
        services.AddAWSService<IAmazonSQS>(lifetime: ServiceLifetime.Transient);
    }

I've seen many examples go with the default, but reading the is article suggests going with Transient unless there is a reason to go with Singleton: https://dotnetcoretutorials.com/2017/03/25/net-core-dependency-injection-lifetimes-explained/#comments

Josh
  • 8,219
  • 13
  • 76
  • 123
  • 1
    If we're not sure what the lifetime should be, Transient is safer because we won't mess something up. The article you linked is more general, not about AWS. In the case of AWS, they know what their internals are so they know which makes more sense. It implies that they designed their classes to work well that way. There's no 100% certain guarantee, but unless there's a known reason I'd lean toward the default. For example, what if one of their classes uses an `HttpClient`, and their default lifetime keeps it from getting created and disposed incorrectly? – Scott Hannen Jun 07 '19 at 20:34

1 Answers1

2

From a dev of the AWS SDK I recommend leaving it at the default. The AWS service clients added to the collection are thread safe. We added the overload to set the service lifetime to provide flexibility in case somebody is doing some really unusual.

Norm Johanson
  • 2,964
  • 14
  • 13