Search code examples
c#attributesaoppostsharp

Possible to inject dynamic code using PostSharp AOP


Assuming I create a custom PS attribute InjectCodeAttribute which I apply to a class or class member, would it be possible to tell PostSharp to replace the attribute with dynamic C# code provided as a string.

For example, can I turn this:

[InjectCodeAttribute] public class MyClass

into this:

[DependencyProperty, Obfuscation(Feature = "renaming", Exclude = true, StripAfterObfuscation = true)] public class MyClass

by providing this string [DependencyProperty, Obfuscation(Feature = "renaming", Exclude = true, StripAfterObfuscation = true)] to the InjectCodeAttribute attribute?

Note: I am aware of the Custom Attributes functionality provided by PostSharp http://doc.postsharp.net/attribute-introduction and that I could create an attribute that injects the example attribute, but I just want to know if it's possible to inject any code (even invalid code that maybe throws an exception/error during compilation) I provide as a string.


Solution

  • The answer is no for the described use case. PostSharp runs after the C# compilation has already completed and processes the binary assembly. At this point it's already too late to add a string input for C# compiler.