How to inject a new code in existing C# code (not MSIL) before compiling, but not change .cs file?
Asked
Active
Viewed 2,338 times
2
-
Using partial methods/class can't help ? – Felice Pollano Mar 28 '11 at 20:35
-
No, it doesn't help. I need to inject a lot of similar code in different properties of classes. – Aleksandr Vishnyakov Mar 28 '11 at 20:38
4 Answers
3
You can use the Text Template Transformation Toolkit (T4) to handle this type of scenario.

Reed Copsey
- 554,122
- 78
- 1,158
- 1,373
3
Use T4 templates which write to partial class files. This is the pattern used by Visual Studio--auto-generated code goes in partial files, while your code goes in the main .cs file.
2
You may take a look at PostSharp.

Darin Dimitrov
- 1,023,142
- 271
- 3,287
- 2,928
-
With PostSharp, I can inject code in runtime, but not before compiling. – Aleksandr Vishnyakov Mar 28 '11 at 20:33
-
I'm pretty sure PostSharp injects code after compilation, but before runtime. – Giovanni Galbo Mar 28 '11 at 20:38
-
See compile time weaving: http://www.sharpcrafters.com/aop.net/compiletime-weaving – Giovanni Galbo Mar 28 '11 at 20:39
-
You says: "I'm pretty sure PostSharp injects code AFTER compilation...", but I need to inject code BEFORE compilation. – Aleksandr Vishnyakov Mar 28 '11 at 20:43
-
I know, I'm correcting you, "With PostSharp, I can inject code in runtime" – Giovanni Galbo Mar 28 '11 at 20:45
1
You can using Fody or Weavlyn which working with MSIL injection "IL Weaving"

Osama AbuSitta
- 3,918
- 4
- 35
- 51