What is IL Weaving?

IL Weaving is the process of modifying compiled Intermediate Language (IL) code in .NET assemblies after compilation but before execution. This technique enables developers to inject, modify, or remove code dynamically without altering the original source code.

It is commonly used for Aspect-Oriented Programming (AOP), performance optimizations, and enforcing security policies dynamically.

Why is IL Weaving Useful?

IL Weaving provides several advantages:

When to Use IL Weaving?

Use IL Weaving when:

Where to Use IL Weaving?

IL Weaving is commonly used in:

How to Use IL Weaving?

1. Using Mono.Cecil for Advanced IL Manipulation

If you need low-level IL modifications, you can use Mono.Cecil to rewrite compiled assemblies manually.

Step 1. Install Mono.Cecil

PowerShell
Install-Package Mono.Cecil

Step 2. Modify an Assembly at Runtime

This example dynamically injects a Console.WriteLine() statement into a method inside a compiled assembly:

C#
using Mono.Cecil;
using Mono.Cecil.Cil;
using System;

class Program
{
    static void Main()
    {
        var assembly = AssemblyDefinition.ReadAssembly("YourAssembly.dll");
        var type = assembly.MainModule.GetType("YourNamespace.YourClass");
        var method = type.Methods.First(m => m.Name == "YourMethod");

        // Create IL processor
        var il = method.Body.GetILProcessor();
        il.InsertBefore(method.Body.Instructions[0], il.Create(OpCodes.Ldstr, "Injected Code!"));
        il.InsertBefore(method.Body.Instructions[1], il.Create(OpCodes.Call, assembly.MainModule.ImportReference(typeof(Console).GetMethod("WriteLine", new[] { typeof(string) }))));

        // Save modified assembly
        assembly.Write("YourModifiedAssembly.dll");
    }
}

Result. This will inject a Console.WriteLine("Injected Code!") into YourMethod() dynamically at runtime!

Important Notes & Considerations for IL Weaving

1️⃣ Not Supported in .NET Native or AOT (Ahead-of-Time) Compiled Apps ⚠️

2️⃣ Requires Full Trust Execution 🔐

3️⃣ Debugging IL-Weaved Code Can Be Challenging 🧐

4️⃣ Can Increase Build Time in Large Projects ⏳

5️⃣ Might Break with Future .NET Versions 🔄

Supported .NET Versions

✅ Works in

❌ Not Recommended for

📌 Best Practices for IL Weaving in .NET

  1. Use Fody for high-level AOP scenarios (e.g., logging, security policies, performance tracing).
  2. Use Mono.Cecil for low-level IL modification when full control is needed.
  3. Avoid IL Weaving in sandboxed or AOT environments—use source generators instead.
  4. Test IL modifications thoroughly, as debugging is harder than regular C# code.
  5. Always validate assembly integrity after IL weaving to prevent corruption.