Reputation: 24190
I'm trying to use the following by calling: StaticClass.DeleteObject(null, key)
. It didn't work as I expected, and the code in the lambda expression throws a NullReferenceException because context is null, which is understandable. I tried changing the context parameter of AmazonS3Operation to a ref, but ReSharper then warns of "Access to modified closure."
Basically I'm just trying to "inject" the lambda expression in that helper method, then call it, if you get the idea of how I'd like it to work. Is this possible, or what could I do that's similar if not?
/// <exception cref="IOException"></exception>
public static void DeleteObject(this AmazonS3Context context, string key)
{
AmazonS3Operation(context, () => context.Client.DeleteObject(
new DeleteObjectRequest().WithBucketName(context.CurrentBucket)
.WithKey(key)));
}
/// <exception cref="IOException"></exception>
private static void AmazonS3Operation(AmazonS3Context context, Action operation)
{
var shouldDispose = false;
try
{
if (context == null)
{
context = new AmazonS3Context();
shouldDispose = true;
}
operation();
}
catch (AmazonS3Exception e)
{
throw new IOException(e.Message, e);
}
finally
{
if (shouldDispose)
context.Dispose();
}
}
Upvotes: 1
Views: 1906
Reputation: 3360
Use a local variable in the method instead of modifying your parameter:
AmazonS3Context localContext = context;
try {
if (locaContext == null) {
// keep using localContext...
And have your Action be
Action<AmazonS3Context>
so you can pass in the instance instead of relying on a closure. The method being called already has the instance you want as its other parameter, so using a closure here would be considered harmful.
Upvotes: 1
Reputation: 2586
I would pass the context into the action. Replace the Action parameter with an Action<AmazonS3Context> parameter.
/// <exception cref="IOException"></exception>
public static void DeleteObject(this AmazonS3Context context, string key)
{
context = null;
AmazonS3Operation(context, ctx => ctx.Client.DeleteObject(
new DeleteObjectRequest().WithBucketName(ctx.CurrentBucket)
.WithKey(key)));
}
/// <exception cref="IOException"></exception>
private static void AmazonS3Operation(AmazonS3Context context, Action<AmazonS3Context> operation)
{
var shouldDispose = false;
try
{
if (context == null)
{
context = new AmazonS3Context();
shouldDispose = true;
}
operation(context);
}
catch (AmazonS3Exception e)
{
throw new IOException(e.Message, e);
}
finally
{
if (shouldDispose)
context.Dispose();
}
}
Upvotes: 3