Say I have a web service that works with a database. Each method opens the database, and then of course closes it on exit.
Is there any method to move the open/close code outside the web method itself? Something like OnBeforeWebMethodCalled / OnAfterWebMethodCalled.
So instead of
[WebMethod]
public void Hello()
{
OpenDatabase();
try { } finally { CloseDatabase(); }
}
we will have
private void OnBeforeWebMethodCalled() { OpenDatabase(); }
private void OnAfterWebMethodCalled() { CloseDatabase(); }
[WebMethod]
public void Hello()
{
// the database is ready here
}
Thanks everybody for suggesting the using keyword but I know about it. The problem is that I have a legacy service of first kind and I'd like to easily wrap the database stuff to make it the second kind.
Now, imagine it's not a database stuff. Imaging I'd like to log web methods entry/exit. Or I want to send emails about which method is called. Whatever. What I really need is to execute some code at entry/exit of the web method. And I don't want to inject this code into every single web method. Ideally if I can catch exceptions, too.