Chapter 7. Generating code with IL rewriting
This chapter covers
- The benefits of code rewriting
- Using libraries to rewrite assemblies
- Debugging injected code
Throughout part 2 (beginning in chapter 3) you’ve seen a number of techniques and frameworks that you can use to generate code at various stages of execution. But there’s one area of code execution that we’ve not yet addressed. It’s after compilation, when your code has been turned into IL that’s stored in an assembly. At that point, your code is in a format that the CLR uses to run your code, and most developers think the assembly is frozen at that point—that it can’t be changed. But that’s not the case!
In this chapter, you’ll see how to rewrite assemblies to inject common code aspects or to add instrumentation to code. You’ll understand the benefits of code injection and what libraries you’ll need to use to pull off this technique. By the end, you’ll have a powerful tool in your metaprogramming toolkit that will allow you to parcel small, reusable code concepts across multiple applications. The result is code that looks lean, yet contains all the implementations you want.
As always, we start with an explanation of the benefits of injecting code.