IL weaving for C# programmers / Fody library and AOP
Presentation for the talk I gave during Meet.NET Szczecin
Please find the code samples here
https://1drv.ms/u/s!Apg9TvTsYIs3sAGPmF5Mkhx-xadl
2. Agenda
• .net Compilation Process
• Intermediate language and what can we do with it
• What can we do with it?
• Aspect Oriented Programming
• … and why we shouldn’t
• Fody
• Code samples
4. Intermediate Language
• Firstly known as MSIL, later renamed to CIL
• Platform independent instructions
• Enriched with metadata
• Very similar to assembly languages
• Can be translated into assembly
• By JIT (Just in time) compiler
• By ngen.exe to build native image
• By building universal app
6. What can we do with IL?
• Usually – nothing
• Really – we shouldn’t
• Reflection.Emit
• Precompiled, instead of reflection (ie type descriptors)
• Dynamic proxies
• Mocks (moq)
• Poor man’s AOP, patterns design
• Postsharp $$$
• Enriching code without making mess
• Fody (free!)
7. Theory: Aspect Oriented Programming
• Created for better concerns separation
• Based on advices
• Always log the call when method name begins with „Set”
• Always check for login token when the service is called
• Allows less cluttered code
• Commonly implemented by weaving
• Pre-compilation weaving (C++ preprocesor)
• Post-compilation weaving (C# IL, Java bytecode)
8. Typical AOP proces (advice)
BeforeAdvice
Always call me
before Method()
Method()
AfterAdvice
Always call me
after Method()
Normal
control
flow
Normal
control
flow
9. Typical uses of IL Weaving / AOP
• INotifyPropertyChanged
• Logging
• Null-checking
• Permissions-checking
• Undo-redo pattern
• Freeze pattern
• Method call cache
• Global handling of exceptions
• Encrypting string literals
• … and many more
10. The criticism of AOP
• Losing control of „what-where” (obscuring control flow)
• Error propagation
• Programmers afraid
• Crosscutting means no one can be an expert in part of code
• AOP is patented!
11. Meal of the day: Fody
• Free and open source
• Plugin architecture
• No artifacts in your output
• No references
• No installs
• Works in MSBuild
• Doesn’t break your compilation (signing, strong name)
• „Install-Package Fody”