As the new year (2025) starts, I want to share some insights from my role at Xari. While Javier and I founded the company together (he’s the Chief in Command, and I’ve dubbed myself the Minister of Dark Magic), our rapid growth has made these playful titles more meaningful than we expected.

Among my self-imposed responsibilities are:

  • Providing ancient knowledge to the team (I’ve been coding since MS-DOS 6.1 – you do the math!)
  • Testing emerging technologies
  • Deciphering how and why our systems work
  • Achieving the “impossible” (even if impractical, we love proving it can be done)

Our Technical Landscape

As a .NET shop, we develop everything from LOB applications to AI-powered object detection systems and mainframe database connectors. Our preference for C# isn’t just about the language – it’s about the power of the .NET ecosystem itself.

.NET’s architecture, with its intermediate language and JIT compilation, opens up fascinating possibilities for code manipulation. This brings us to one of my favorite features: Reflection, or more broadly, metaprogramming.

Enter Harmony: The Art of Runtime Magic

Harmony is a powerful library that transforms how we approach runtime method patching in .NET applications. Think of it as a sophisticated Swiss Army knife for metaprogramming. But why would you need it?

Real-World Applications

1. Performance Monitoring


[HarmonyPatch(typeof(CriticalService), "ProcessData")]
class PerformancePatch
{
    static void Prefix(out Stopwatch __state)
    {
        __state = Stopwatch.StartNew();
    }
    
    static void Postfix(Stopwatch __state)
    {
        Console.WriteLine($"Processing took {__state.ElapsedMilliseconds}ms");
    }
}
        

2. Feature Toggling in Legacy Systems


[HarmonyPatch(typeof(LegacySystem), "SaveToDatabase")]
class ModernizationPatch
{
    static bool Prefix(object data)
    {
        if (FeatureFlags.UseNewStorage)
        {
            ModernDbContext.Save(data);
            return false; // Skip old implementation
        }
        return true;
    }
}
        

The Three Pillars of Harmony

Harmony offers three powerful ways to modify code:

1. Prefix Patches

  • Execute before the original method
  • Perfect for validation
  • Can prevent original method execution
  • Modify input parameters

2. Postfix Patches

  • Run after the original method
  • Ideal for logging
  • Can modify return values
  • Access to execution state

3. Transpilers

  • Modify the IL code directly
  • Most powerful but complex
  • Direct instruction manipulation
  • Used for advanced scenarios

Practical Example: Method Timing

Here’s a real-world example we use at Xari for performance monitoring:


[HarmonyPatch(typeof(Controller), "ProcessRequest")]
class MonitoringPatch
{
    static void Prefix(out Stopwatch __state)
    {
        __state = Stopwatch.StartNew();
    }

    static void Postfix(MethodBase __originalMethod, Stopwatch __state)
    {
        __state.Stop();
        Logger.Log($"{__originalMethod.Name} execution: {__state.ElapsedMilliseconds}ms");
    }
}
        

When to Use Harmony

Harmony shines when you need to:

  • Modify third-party code without source access
  • Implement system-wide logging or monitoring
  • Create modding frameworks
  • Add features to sealed classes
  • Test legacy systems

The Dark Side of Power

While Harmony is powerful, use it wisely:

  • Avoid in production-critical systems where stability is paramount
  • Consider simpler alternatives first
  • Be cautious with high-performance scenarios
  • Document your patches thoroughly

Conclusion

In our work at Xari, Harmony has proven invaluable for solving seemingly impossible problems. While it might seem like “dark magic,” it’s really about understanding and leveraging the powerful features of .NET’s architecture.

Remember: with great power comes great responsibility. Use Harmony when it makes sense, but always consider simpler alternatives first. Happy coding!