Sanjay Sutar
Sanjay Sutar

Reputation: 544

using attribute to read Method Parameters

I want to log the entry of methods. In entry log I would have inputs\parameters received by the method. This has to be done for thousands of methods.

I thought of doing this logging of input parameters using C# ATTRIBUTES, since they fired before method call. (Something similar to ActionFilters in MVC)

Is that possible to read method parameters through attributes?

Upvotes: 0

Views: 358

Answers (2)

haim770
haim770

Reputation: 49095

  1. Attributes are not 'fired before method call', the code that invokes a method that is decorated with an Attribute may (or may not) do something based on the presence of the Attribute.

  2. The Attribute doesn't know the member it is applied on, nor can access it in any (straight forward) way.

Upvotes: 1

Markus
Markus

Reputation: 22421

The concept you are looking for is called aspect oriented programming (AOP). It is a technique that allows you to "weave" in blocks of boilerplate code across your application code. Logging is a perfect example for that. You can either go the hard way and implement logging before and after each method call manually (which is on the one hand not feasible in large projects and on the other hand error prone).
Or you can use an AOP Framework that allows you to define these cross cutting functions in one place and apply it declaratively to your application code. There are several approaches to achieve this; one is to create IL after the build of the application logic and therefore integrating the aspects at compile time. A well known example for this is PostSharp. There also is a free edition that is good for the start.
BTW: PostSharp heavily relies on attributes, so you're on the right track.
Another option is to integrate the aspects at run time (keyword is interception). Most IoC Frameworks offer this. This approach is easy to use but has some downsides IMHO (weaker runtime Performance, only virtual methods can be intercepted).

Upvotes: 1

Related Questions