Base class for an ASMX webservice - calling the derived method from the base class it self
I have a bunch of asmx web services, and in all the methods inside the webservices follow a common pattern
public virtual TestObject Test()
{
LogRequest;
try
{
DoSomething;
}
catch
{
LogException;
}
LogResponse;
return response;
}
and all the methods follow this pattern, there is a lot of code repetition; I want to know if there is a way to do this generically ie: may be in a base class con开发者_StackOverflow社区structor? is it even possible?
EDIT:
The Template Method pattern was a good solution, but in the End the most elegant solution for us was AOP!! the logging was all extracted out in to an aspect and all methods that needed logging were decorated using an attribute and post sharp rules!
You can have a method somewhere (in a base class or declared static anywhere) that does all the common stuff:
T DoCommon<T>(Request r, Func<T> f)
{
LogRequest(r);
T result;
try { result = f(); }
catch(Exception ex) { LogException(ex); }
LogResult(result);
return result;
}
And then you'd only have to include a call to that method:
public virtual TestObject Test()
{
return DoCommon(Request, () => DoSomething());
}
It sounds like you're looking for the Template Method pattern. That pattern allows you to define a series of steps in the superclass (and default implementations of those steps, if applicable) - then subclasses need only override the steps relevant to their specific processing.
The Template Method pattern was a good solution, but in the End the most elegant solution for us was AOP!! the logging was all extracted out in to an aspect and all methods that needed logging were decorated using an attribute and post sharp rules!
精彩评论