Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disposing the AmazonS3Client and S3Response

I've looked at a number of examples of how to use the AmazonS3Client and S3Response objects and never have I seen anyone bothering to dispose of them, which makes me wonder is there some implied knowledge that I am missing?

public class S3Response : IDisposable
{
    public void Dispose();
    ~S3Response();
}

public class AmazonS3Client : AmazonS3, IDisposable
{
    public void Dispose();
    ~AmazonS3Client();
}

They both clearly implement IDisposable (which is telling me I should be disposing them myself) but they also specify a destructor method, which (along with the aforementioned examples) is making me think have I missed something automagical?

Could it be that the destructor is calling Dispose behind the scenes? Surely it is bad form to perform this kind of magic behaviour.

Does anyone with more experience of the Amazon S3 service have any insight to offer?

like image 939
gingerbreadboy Avatar asked Oct 20 '22 17:10

gingerbreadboy


1 Answers

First, Destructors are called automatically by the C# Garbage Collector when the object is marked as eligible for destruction, which then calls Finalize. Keep in mind, it could be a long time before the GC runs and decides to do this, and you don't have any real control over it besides manually calling the GC which is not recommended.

Most tutorials only show very basic usage of the libraries, you should definitely be disposing these objects yourself though. (or any object that implements IDisposable)

You of course could do it in a using statement

using(var client = new AmazonS3Client())
{
    // use the client here in the using scope
}
// the Dispose() is called after you leave scope of using statement

However, in general some objects are expensive to create (and destroy) and are more meant to be re-used for an extended period of time for several requests. In this case (and probably for the S3Client) you would keep and re-use the same reference to the S3Client for a longer duration then just one request. Keep in mind every time you instantiate the S3Client, it is probably authenticating with Amazon which is time-consuming and expensive.

Say you have a website using the S3Client. You probably want to re-use the same S3Client over the entirety of a web request, or even several web requests. You can achieve this by a Singleton pattern or even a dependency injector library like Unity which you can define an object Lifetime Manager which.

like image 129
SlaterCodes Avatar answered Oct 30 '22 19:10

SlaterCodes