views:

68

answers:

1

I'd like to have property getters and methods that I can decorate with my own custom attribute and based on the presence of that attribute replace the method bodies with a different implementation. Also, that different implementation will need to know the constructor arguments given to the custom attribute where it decorates the method.

This can obviously be done with AOP, like PostSharp or LinFu, but I'm wondering if there's a way to do this that does not involve a post-build processing step because adding that complicates the project more than I would prefer.

A: 

Using the traditional .Net APIs there is no way to achieve this. Method bodies are fixed at compile time and cannot be changed.

I say traditional though because with the profiler and ENC APIs it's technically possible to change method bodies. But these APIs operate in constrained circumstances and are not considered to be general purpose APIs.

JaredPar
But it most definitely can be done. .Net AOP frameworks perform modifications like this. NHibernate dynamically proxies whole classes. Just because there's not a System.Reflection.Method.ReplaceWith(...) doesn't mean I can't do this without excessive complexity, I'm sure.
qstarin
@qstarin while I'm not familiar with all of them I know that some of these frameworks achieve this by modifying the IL directly and not while the process is executing. There is no traditional .Net API that provides this capability.
JaredPar
hrm ... sticky problem. I don't really like any of the AOP's way of doing this.
qstarin
I was loathe to accept your answer initially. But after even more research I think I have to accept that you are in fact correct. I cannot find any leads on any reasonable way to accomplish this without leveraging a post-build AOP step.Although ... ayende hints at something that piques my curiosity: http://ayende.com/Blog/archive/2009/11/19/can-you-hack-this-out.aspx
qstarin