patterncsharpMinor
Do you like this kind of helper, which creates short lived helper objects through a delegate?
Viewed 0 times
thiscreatesyoushorthelperlivedobjectslikekinddelegate
Problem
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
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 action)
{
using (var context = new EomTool.Domain.Entities.EomEntities(EomAppCommon.EomAppSettings.ConnStr, false))
{
var repository = new EomTool.Domain.Concrete.PaymentBatchRepository(context);
action(context, repository);
}
}Solution
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
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.
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 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.
Context
StackExchange Code Review Q#20664, answer score: 6
Revisions (0)
No revisions yet.