Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Just curious if this is a reasonable idea. I wouldn't do it all the time. The example I'm in now is that of the data context and repository that uses it.

I kind of like this because, compared to calling new in AssignButtonClicked, it gives my code the same quality of feeling independent of resource allocation as when using constructor injection (which I can't do for short lived resources).

void AssignButtonClicked(object sender, EventArgs e)
{
    WithPaymentBatchRepository((context, repository) =>
    {
        foreach (var itemIDs in this.SelectedItemIdsAsInts)
        {
            repository.SetPaymentBatchId(itemIDs, this.SelectedPaymentBatchId);
        }

        context.SaveChanges();
    });

    Refill();
}

static void WithPaymentBatchRepository(Action<EomTool.Domain.Entities.EomEntities, EomTool.Domain.Concrete.PaymentBatchRepository> action)
{
    using (var context = new EomTool.Domain.Entities.EomEntities(EomAppCommon.EomAppSettings.ConnStr, false))
    {
        var repository = new EomTool.Domain.Concrete.PaymentBatchRepository(context);
        action(context, repository);
    }
}
share|improve this question
1  
Is WithPaymentBatchRepository going to be called elsewhere or only from AssignButtonClicked? Or there gonna be other helper methods of the same style for other user actions? –  Max Yakimets Jan 18 '13 at 11:24

1 Answer 1

up vote 6 down vote accepted

it gives my code the same quality of feeling independent of resource allocation as when using constructor injection

But it's not. With constructor injection, the caller can easily use another implementation or create the resource with different parameters. With your helper method, that is gone. And you can use constructor injection with short lived resources: inject a factory for that resource (that could be a simple Func<Resource> delegate or an interface) instead of the resource itself.

All in all, your helper method might be useful to avoid repeating common code, but not much else. And even with that, it doesn't help much.

share|improve this answer
    
that's a good idea to inject a factory. thanks for the tip! –  Aaron Anodide Jan 18 '13 at 19:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.