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:
- ✅ Code Injection Without Source Modification: Modify assemblies without changing the original C# or VB.NET source code.
- ✅ Aspect-Oriented Programming (AOP) Implementation: Easily add logging, security checks, or metrics without modifying business logic.
- ✅ Performance Optimization: Inject performance enhancements dynamically based on runtime conditions.
- ✅ Reduce Boilerplate Code: Automate repetitive logic like logging, tracing, and error handling.
- ✅ Security & Compliance Enforcement: Inject security policies into an assembly before deployment.
When to Use IL Weaving?
Use IL Weaving when:
- You need to modify behavior across multiple assemblies without refactoring the source code.
- You want to inject logging, metrics, or profiling without touching the core application logic.
- You are implementing AOP (Aspect-Oriented Programming) in .NET applications.
- You need to enforce security policies dynamically across multiple services.
- You want to optimize code performance based on runtime conditions.
Where to Use IL Weaving?
IL Weaving is commonly used in:
- Enterprise Applications: Inject security policies, logging, or tracing dynamically.
- Microservices & Distributed Systems: Apply cross-cutting concerns (e.g., request tracing, performance monitoring) dynamically.
- Game Development: Modify game logic dynamically without recompiling the whole game engine.
- Performance-Critical Applications: Optimize code dynamically for runtime execution.
- Code Generation & Obfuscation: Transform assemblies for security and efficiency.
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
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:
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 ⚠️
- IL Weaving modifies assemblies post-compilation, but in .NET Native (UWP) or AOT (Blazor WebAssembly, iOS, Android), assemblies are precompiled, making IL modification impossible.
- Solution: Use source generators for AOT scenarios.
2️⃣ Requires Full Trust Execution 🔐
- IL Weaving works only in Full Trust environments (e.g., ASP.NET Core, Console Apps, Windows Services).
- It does not work in sandboxed environments like Azure Functions Consumption Plan.
- Solution: Use dependency injection-based AOP alternatives (like Castle DynamicProxy) in restricted environments.
3️⃣ Debugging IL-Weaved Code Can Be Challenging 🧐
- Since IL Weaving modifies the compiled assembly, debugging can be difficult because the original source code does not match the modified IL.
- Solution: Use tools like ILSpy, dnSpy, or DotPeek to inspect the modified IL.
4️⃣ Can Increase Build Time in Large Projects ⏳
- If used extensively, IL Weaving tools like Fody can slightly increase build time, as they modify assemblies after compilation.
- Solution: Use IL Weaving only for critical cross-cutting concerns and optimize build steps.
5️⃣ Might Break with Future .NET Versions 🔄
- IL structures can change across .NET versions, which may break IL manipulation libraries like Mono.Cecil or Fody.
- Solution: Always test IL weaving techniques after major .NET updates.
Supported .NET Versions
✅ Works in
- .NET Framework 4.5+
- .NET Core 2.1, 3.1
- .NET 5, .NET 6, .NET 7, .NET 8
❌ Not Recommended for
- .NET Native (UWP/Xamarin iOS/Android AOT Compilation)
- Blazor WebAssembly (Client-Side)
- Azure Functions in Consumption Plan (Sandboxed Environment)
📌 Best Practices for IL Weaving in .NET
- Use Fody for high-level AOP scenarios (e.g., logging, security policies, performance tracing).
- Use Mono.Cecil for low-level IL modification when full control is needed.
- Avoid IL Weaving in sandboxed or AOT environments—use source generators instead.
- Test IL modifications thoroughly, as debugging is harder than regular C# code.
- Always validate assembly integrity after IL weaving to prevent corruption.