Detour Order
When several mods hook the same method, MonoMod.RuntimeDetour keeps all their detours in a single detour chain and decides who runs first. This page explains DetourConfig (IDs, before/after, priority), DetourContext (ambient configuration), and the exact ordering algorithm implemented in DetourManager.Shared.cs.
- The detour chain
- DetourConfig
- Ordering rules
- DetourContext: ambient configuration
- The ordering algorithm
- Conflicts and cycles
The Detour Chain
All detours whose source is the same method belong to one chain. When the method is called, the first detour in the chain runs. Its orig delegate calls the second, and so on; the last orig calls the original method (with any ILHook changes). "Runs first" therefore means "is the outermost wrapper": its code before orig runs first and its code after orig runs last.
Hook and NativeHook detours are ordered in their chain. ILHook manipulators use the same rules to decide the order in which they are invoked on the IL.
DetourConfig
public class DetourConfig
{
public DetourConfig(string id, int? priority = null,
IEnumerable<string>? before = null,
IEnumerable<string>? after = null);
public string Id { get; }
public int? Priority { get; }
public IEnumerable<string> Before { get; }
public IEnumerable<string> After { get; }
public int SubPriority { get; } // advanced, hidden from IntelliSense
}
| Property | Type | Default | Meaning |
|---|---|---|---|
Id |
string |
(required) | Identifies the detours created with this config, typically the mod's name. Several detours may share one ID. |
Priority |
int? |
null |
Higher values run earlier. Detours with a priority run before detours without one, unless Before/After say otherwise. |
Before |
IEnumerable<string> |
empty | IDs of detours that this detour must run before (this detour is placed earlier in the chain). |
After |
IEnumerable<string> |
empty | IDs of detours that this detour must run after. |
SubPriority |
int |
0 |
Tie-breaker among detours with the same Priority: higher runs first. Marked EditorBrowsable(Never); only for advanced use. |
Before and After take precedence over Priority.
Note: The XML doc comments on
Before/Afterread "Gets the detour IDs to run before this detour", which suggests the opposite direction. The ordering code and theDetourOrderTestunit test agree with the table above: a config withBefore = ["A"]runs earlier than detours with IDA.
Builder Methods
DetourConfig is immutable. These methods return modified copies:
| Method | Result |
|---|---|
WithPriority(int? priority) |
Same config, new priority. |
WithBefore(IEnumerable<string>) / WithBefore(params string[]) |
Replaces Before. |
WithAfter(IEnumerable<string>) / WithAfter(params string[]) |
Replaces After. |
AddBefore(...) / AddAfter(...) |
Appends to the existing list. |
var cfg = new DetourConfig("MyMod")
.WithPriority(10)
.AddAfter("CoreLib") // run after CoreLib's hooks
.AddBefore("UiTweaks"); // and before UiTweaks' hooks
The before and after sequences are copied to an array at construction (unless they already are a collection), so later changes to a lazily evaluated sequence do not leak in.
Ordering Rules
The final chain is: all detours with a config, in graph order, followed by all detours without a config.
| Situation | Result |
|---|---|
A.Before contains B |
A runs before every detour with ID B. |
A.After contains B |
A runs after every detour with ID B. |
No before/after relation, both have priorities |
Higher Priority runs first; for equal priorities, higher SubPriority runs first. |
| One has a priority, the other does not | The one with a priority runs first. |
| Neither has a priority nor a relation | Order of application: a newly applied detour is inserted after existing ones with the same (null) priority. |
No config at all (Hook/NativeHook) |
Runs after every configured detour. The most recently applied no-config detour runs first (they are pushed onto a stack). |
No config at all (ILHook) |
Manipulators run after the configured ones, in application order. |
Example from the Test Suite
DetourOrderTest.TestDetoursOrder applies four hooks to the same method, in this order:
- no config (
"Default"), new DetourConfig("AfterA").AddAfter("A"),- config
Ataken from an ambientDetourConfigContext, new DetourConfig("BeforeA").AddBefore("A").
The observed execution order is BeforeA, A, AfterA, Default.
DetourContext: Ambient Configuration
Passing a DetourConfig to every constructor is tedious. A DetourContext makes a config (and/or a detour factory) ambient for the current thread:
using (new DetourConfigContext(new DetourConfig("MyMod", priority: 5)).Use())
{
// Every Hook / ILHook / NativeHook created here without an explicit config
// gets DetourConfig "MyMod" with priority 5.
new Hook(m1, target1);
new ILHook(m2, manipulator);
}
| Type | Provides |
|---|---|
DetourContext |
Abstract base. Use() pushes it onto a thread-static stack and returns a disposable DataScope that pops it. |
EmptyDetourContext |
Abstract base that provides nothing; derive from it to override only one of the two. |
DetourConfigContext(DetourConfig? cfg) |
Provides a config. Passing null provides "no config", which hides outer contexts' configs. |
DetourFactoryContext(IDetourFactory fac) |
Provides a detour factory. |
Lookup Rules
| API | Behavior |
|---|---|
DetourContext.GetDefaultConfig() / CurrentConfig / TryGetCurrentConfig(out cfg) |
Walks the thread's context stack from the innermost active scope outwards and returns the first config provided; then the global context; otherwise null. |
DetourContext.GetDefaultFactory() |
The first factory provided by the stack or global context, otherwise DetourFactory.Current. |
DetourContext.Current |
The innermost active context on this thread, or the global one. |
DetourContext.SetGlobalContext(ctx) |
Sets a process-wide fallback context (checked after the thread's stack) and returns the previous one. Marked EditorBrowsable(Advanced). |
Contexts are thread-static: a context pushed on one thread does not affect hooks created on another thread, and it does not flow into async continuations that resume on other threads. The config is read once, in the hook's constructor; changing contexts later does not reorder existing hooks.
Note: An explicit
configargument always wins over the context, including an explicitnullpassed to a constructor that takesDetourConfig? config. Only the overloads without aconfigparameter consult the context.
The Ordering Algorithm
The configured detours of a chain form a dependency graph. Each node has a BeforeThis list of nodes that must execute before it. When a node N is inserted, for every existing node C:
- If
N.BeforecontainsC.Id,Nis added toC.BeforeThis. - If
N.AftercontainsC.Id,Cis added toN.BeforeThis. - If
C.BeforecontainsN.Id,Cis added toN.BeforeThis. - If
C.AftercontainsN.Id,Nis added toC.BeforeThis.
Insertions into a BeforeThis list, and into the list of all nodes, are priority-sorted: higher Priority first, nodes without priority at the end, and within equal priority, higher SubPriority first.
The graph is then flattened: MonoMod walks the list of all nodes and, for each, recursively emits its BeforeThis nodes and then the node itself, skipping nodes already emitted. The result is the chain order. Removing a detour removes its node from every list and flattens again.
Conflicts and Cycles
- Direct contradictions (for example
AbeforeBwhileBalso says it is beforeA, or one config listing the same ID in bothBeforeandAfter) are detected while inserting. MonoMod logs a warning,Detour 'A' is marked as being both before and after 'B', and ignores the contradicting edge. The resulting order between the two is not specified. - Longer cycles (
AbeforeB,BbeforeC,CbeforeA) are not caught by that check. Flattening detects them and throwsInvalidOperationException("Cycle detected"), so applying the detour that closes the cycle fails. - After a cycle error, be careful. In
AddDetour, the rollback that removes a half-added node only runs once the node has been inserted successfully; the cycle is thrown during insertion, after the node was already added to the graph's node list. Reading the code, the offending node therefore stays in the graph, and later additions or removals of configured detours on that same method can keep failing with the same exception. Avoid cycles rather than relying on recovery.
Keep relations minimal: prefer after on the dependency you know about, and use priorities only for coarse layering.
See Also
- Hook
- ILHook
- Introspection and Thread Safety
- Switches and Logging (to see ordering warnings)