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.

7.1. The case for code injection

Before we dive into the details of IL rewriting, let’s start with a couple of examples that illustrate the need to rewrite assemblies: reducing recurring implementations and restructuring code flow.

7.1.1. Repeated implementations of coding patterns

7.2. Creating an injection framework

7.3. Debugging injected code

7.4. Summary

sitemap