Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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);



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
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
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


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.