tags:

views:

63

answers:

1

I have three methods:

public void Save<T>(T entity)
{
    using (new Transaction())
    {
        Session.Save(entity);
    }
}

public void Create<T>(T entity)
{
    using (new Transaction())
    {
        Session.Create(entity);
    }
}

public void Delete<T>(T entity)
{
    using (new Transaction())
    {
        Session.Delete(entity);
    }
}

As you can see, the only thing that differs is the method call inside the using block. How can I rewrite this so it's something like this instead:

public void Save<T>(T entity)
{
    TransactionWrapper(Session.Save(entity));
}

public void Create<T>(T entity)
{
    TransactionWrapper(Session.Create(entity));
}

public void Save<T>(T entity)
{
    TransactionWrapper(Session.Save(entity));
}

So in other words, I pass a method call as a parameter, and the TransactionWrapper method wraps a transaction around the method call.

+3  A: 

You can pass an Action<T> to a method to specify an action to execute:

private void ExecuteInTransaction<T>(Action<T> action, T entity)
{
    using (new Transaction())
    {
        action(entity);
    }
}

public void Save<T>(T entity)
{
    ExecuteInTransaction(Session.Save, entity);
}

But IMO this isn't a worthy improvement over your original code if your ExecuteInTransaction method isn't more complex.

dtb
Thanks, it works great. I wanted to wrap the method calls in a transaction method so I can easily enable/disable transactions across all 3 methods in only one place.
Daniel T.