How to combine similar method calls into a delegate template?

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 is different is the method call inside the block using. How can I rewrite this so that there is 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));
}

In other words, I pass the method call as a parameter, and the method TransactionWrapperwraps the transaction around the method call.

+3
source share
1 answer

You can pass 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 is not a worthy improvement over your source code if your ExecuteInTransaction method is not more complex.

+4
source

Source: https://habr.com/ru/post/1743575/


All Articles