And to your second and third question;
Three smooth patterns that I noticed
The first uses the using statement (C # 2.0) to run the code in a specific context, for example:
using(var transaction = new Transaction()) {
This uses the constructor and transaction removal tool to set up the transaction, and then runs the code in this context.
The second does almost the same thing, but with lambda, it is often used in Rhino Mocks, for example.
(new Transaction()).Run( () => mycode(); );
The best-known free interface is to use return types to invoke chained methods. Basically, methods return this, so you can associate calls with the same object. But you can also return different objects to change the context depending on the method called. If you have an object that can only work in a transaction (sorry, I canβt think of another example), you can give it the StartTransaction method, which returns an initialized transaction in which you can start the call and stoptransaction in pseudo-code:
class Runner { Transaction StartTransaction() { return new Transaction(this); } } class Transaction { Transaction Run() Transaction StopTransaction() }
where the call looks like
var runner = new Runner(); runner .StartTransaction() .Run() .StopTransaction();
Of course you need to add all kinds of error handling, etc.
Mendelt Oct 22 '08 at 7:57 2008-10-22 07:57
source share