I currently have an action that I perform on every method in a class as follows:
public void DoSomething(object thing)
{
LogHelper.LogExceptions(() =>
{
//DoSomethingWithThing
});
}
My method contents are all inside the action for LogExceptions. I did this so I didn’t have to have a lot of try, catches and throws all over the show. It works exactly as I want it to, but being the lazy man that I am, I don’t want to keep having to write out the LogExceptions call and nesting my logic in it.
What I want to do is pull up that logic to an attribute, so all I need to do is something like:
[LogExceptions()]
public void DoSomething(object thing)
{
//DoSomethingWithThing
}
Firstly, is this possible, and secondly, does anyone know of any reference material I could use?
Many thanks.
Have a look at an Aspect Oriented Programming (AOP) Framework such as PostSharp. PostSharp allows you to create attributes which you can use to decorate classes, methods…etc.
Such an attribute (or aspect) can be programmed to inject code before your method executes and after its finished.
For example, logging using attributes:
http://www.sharpcrafters.com/solutions/logging
To be complete I’ll include a small example. Let’s say we want to log a message each time a method executes. You can create an aspect (PostSharp attribute) for this purpose.
Here the aspect writes out a message to the console window when the method is finished.
Now you can apply this attribute to a method.
Voila, this makes your method more readable as it is not being cluttered by logging code which adds nothing to the actual functionality of the method (adding two numbers). This results in more readable and maintainable code.
A while back I wrote an article about it on my blog. It’s quite lenghty to copy here, but it demonstrates how to build such attributes and to replace common code such as logging, exception handling…etc. by attributes so that you don’t clutter all of your method with this kind of code:
https://github.com/geersch/PostSharp