# Keeping MEF composition intact under obfuscation


A MEF plugin host has a failure mode that never raises an exception. You obfuscate the solution, ship it, and the host starts up reporting zero plugins — not because a type failed to load, but because `container.GetExports<IPlugin>()` matched nothing and returned an empty sequence. MEF treats "no matching export" as an ordinary result, so there is no stack trace to follow. The composition contract moved, and the only symptom is absence.

The reason is worth understanding exactly, because the fix is precise and the wrong fix — exclude the whole plugin assembly from renaming — throws away the protection you wanted. MEF does not compose by type. It composes by a **contract-name string**, and by default that string is derived from the contract type's full name. Renaming the type changes the string. This post reads where that string comes from, the second naming surface hiding in `[ExportMetadata]`, and how to freeze the composition contract while Nebula flattens everything behind it.

## The real question: what is MEF actually matching on?

Write the smallest plugin host that composes. A contract, an export on the plugin side, an import on the host side:

```csharp
// Contract.dll — referenced by every plugin author.
namespace MyApp.Contracts;

public interface IPlugin
{
    string Run(string input);
}

// Plugin.dll — a third-party plugin, compiled once against Contract.dll.
using System.ComponentModel.Composition;
using MyApp.Contracts;

[Export(typeof(IPlugin))]
public sealed class UpperPlugin : IPlugin
{
    public string Run(string input) => input.ToUpperInvariant();
}

// Host.dll — your loader.
public sealed class Host
{
    [ImportMany]
    public IEnumerable<IPlugin> Plugins { get; set; } = Array.Empty<IPlugin>();
}
```

The intuition is that `[Export(typeof(IPlugin))]` stores "the `IPlugin` type" and MEF matches types. It does not. When MEF reads that attribute it calls `AttributedModelServices.GetContractName(typeof(IPlugin))`, which returns the type's full name as a string — `"MyApp.Contracts.IPlugin"`. That string is the **contract name**, and it is what gets stored in the export definition. The `[ImportMany] IEnumerable<IPlugin>` computes the same string the same way for the import definition. Composition succeeds when, and only when, the two strings are equal (and the export's type is assignable to the import's element type).

You can see the derived name directly:

```csharp
string contract = AttributedModelServices.GetContractName(typeof(IPlugin));
// "MyApp.Contracts.IPlugin"
```

Now the trap is obvious. The contract name is a function of the full type name. Rename `IPlugin` to `a` and `GetContractName` returns `"MyApp.Contracts.a"`. The host, recompiled, computes `"MyApp.Contracts.a"` for its import and matches its *own* newly-renamed export — so your in-house test passes. But the plugin on a customer's disk was compiled against the original contract and still advertises `"MyApp.Contracts.IPlugin"`. The strings differ, the import is unsatisfied, and the plugin vanishes without a word.

<figure class="my-8"><svg viewBox="0 0 760 360" role="img" aria-label="How MEF matches an export to an import by contract-name string. In the default case the export and import contract names are both derived from the full type name MyApp.Contracts.IPlugin, so renaming the interface to a moves the derived string on the export while the shipped plugin still advertises the old string, and the match fails. In the pinned case both sides use an explicit string MyApp.Plugin.v1 that renaming does not touch, so the match holds." style="width:100%;height:auto"><defs><marker id="ar" markerWidth="9" markerHeight="9" refX="7" refY="3" orient="auto"><path d="M0 0l6 3-6 3z" fill="#64748b"/></marker></defs><text x="16" y="24" style="font:600 13px system-ui;fill:#475569">MEF composes by comparing contract-name STRINGS, not types</text><rect x="14" y="40" width="340" height="140" rx="8" fill="#ef4444" fill-opacity="0.07" stroke="#fca5a5" stroke-width="1.5"/><text x="30" y="64" style="font:600 12px system-ui;fill:#dc2626">DEFAULT — name derived from the type</text><text x="30" y="88" style="font:12px ui-monospace,monospace;fill:#475569">[Export(typeof(IPlugin))]</text><text x="30" y="108" style="font:11px system-ui;fill:#64748b">GetContractName(typeof(IPlugin))</text><text x="30" y="128" style="font:12px ui-monospace,monospace;fill:#dc2626">shipped: &quot;MyApp.Contracts.IPlugin&quot;</text><text x="30" y="150" style="font:12px ui-monospace,monospace;fill:#dc2626">renamed: &quot;MyApp.Contracts.a&quot;</text><text x="30" y="170" style="font:600 11px system-ui;fill:#dc2626">strings differ → import empty, no error</text><rect x="406" y="40" width="340" height="140" rx="8" fill="#10b981" fill-opacity="0.07" stroke="#86efac" stroke-width="1.5"/><text x="422" y="64" style="font:600 12px system-ui;fill:#059669">PINNED — explicit string contract</text><text x="422" y="88" style="font:12px ui-monospace,monospace;fill:#475569">[Export(&quot;MyApp.Plugin.v1&quot;, typeof(IPlugin))]</text><text x="422" y="108" style="font:11px system-ui;fill:#64748b">literal string, not derived</text><text x="422" y="128" style="font:12px ui-monospace,monospace;fill:#059669">shipped: &quot;MyApp.Plugin.v1&quot;</text><text x="422" y="150" style="font:12px ui-monospace,monospace;fill:#059669">renamed: &quot;MyApp.Plugin.v1&quot;</text><text x="422" y="170" style="font:600 11px system-ui;fill:#059669">strings equal → import satisfied</text><rect x="110" y="230" width="200" height="56" rx="8" fill="#6366f1" fill-opacity="0.08" stroke="#6366f1" stroke-width="1.5"/><text x="128" y="254" style="font:600 12px system-ui;fill:#6366f1">Export definition</text><text x="128" y="274" style="font:11px ui-monospace,monospace;fill:#475569">ContractName = string</text><rect x="450" y="230" width="200" height="56" rx="8" fill="#0891b2" fill-opacity="0.08" stroke="#0891b2" stroke-width="1.5"/><text x="468" y="254" style="font:600 12px system-ui;fill:#0891b2">Import definition</text><text x="468" y="274" style="font:11px ui-monospace,monospace;fill:#475569">ContractName = string</text><path d="M310 258 h140" stroke="#64748b" stroke-width="1.5" fill="none" marker-end="url(#ar)"/><path d="M450 266 h-140" stroke="#64748b" stroke-width="1.5" fill="none" marker-end="url(#ar)"/><text x="330" y="248" style="font:11px system-ui;fill:#64748b">equal?</text><text x="16" y="326" style="font:11px system-ui;fill:#64748b">The catalog (AssemblyCatalog / DirectoryCatalog / TypeCatalog) only enumerates parts — it adds no second match key.</text><text x="16" y="344" style="font:11px system-ui;fill:#64748b">The match is always string-equality on the contract name plus an assignability check on the export type.</text></svg></figure>

## Pinning the contract so the string stops moving

The robust fix is to stop deriving the contract name from the type. Give the export and the import an explicit string, and that string becomes the contract — independent of what the interface is called in metadata.

```csharp
// Contract.dll — one place both sides import from.
public static class PluginContract
{
    public const string Name = "MyApp.Plugin.v1";
}

// Plugin.dll
[Export(PluginContract.Name, typeof(IPlugin))]
public sealed class UpperPlugin : IPlugin { /* ... */ }

// Host.dll
[ImportMany(PluginContract.Name)]
public IEnumerable<IPlugin> Plugins { get; set; } = Array.Empty<IPlugin>();
```

Now `GetContractName` is never consulted; the export definition carries the literal `"MyApp.Plugin.v1"` and so does the import. Rename `IPlugin` to `a`, rename `UpperPlugin` to `b`, flatten the host — the contract string is unchanged because it is a `const string`, not an identifier. The version suffix (`v1`) is a bonus: it makes the composition contract explicit and versionable, which is good hygiene for a published plugin ABI regardless of obfuscation.

Two names still have to survive even with an explicit string contract, because MEF checks them in addition to the string:

1. **The contract type `IPlugin`.** The second argument to `[Export(..., typeof(IPlugin))]` and the element type of the import are a type-identity check MEF applies on top of the string match. Preserve the interface's name on the contract assembly.
2. **Its members — `Run`.** The host calls `plugin.Run(...)` through the interface. That is an interface method the plugin overrides; rename it on the contract and the plugin's override binds to nothing.

So the explicit string frees the *concrete part* names (`UpperPlugin`, the host's own types) but does not free the contract interface itself. The contract assembly is still a preserve-public-surface boundary; the explicit string just removes the fragile dependency on the exact full type name.

## The second naming surface: metadata and metadata views

MEF's other everyday feature is export metadata, and it hides a naming dependency that the contract-name fix does not cover. A plugin advertises capabilities with `[ExportMetadata]`, and the host reads them through a strongly-typed **metadata view**:

```csharp
// Plugin.dll
[Export(PluginContract.Name, typeof(IPlugin))]
[ExportMetadata("Capability", "pdf")]
[ExportMetadata("Order", 10)]
public sealed class PdfPlugin : IPlugin { /* ... */ }

// Contract.dll — the metadata view interface.
public interface IPluginMetadata
{
    string Capability { get; }
    int Order { get; }
}

// Host.dll
[ImportMany(PluginContract.Name)]
public IEnumerable<Lazy<IPlugin, IPluginMetadata>> Plugins { get; set; }
    = Array.Empty<Lazy<IPlugin, IPluginMetadata>>();
```

There are two different kinds of name here and they behave oppositely under obfuscation.

The **metadata keys** — `"Capability"`, `"Order"` — are string literals stored in the metadata dictionary. They are not identifiers, so renaming never touches them, and they are safe. The **metadata-view interface** is the opposite. MEF materializes `IPluginMetadata` by reading each property name and looking it up as a *key in the metadata dictionary*: the property `Capability` reads the key `"Capability"`, the property `Order` reads the key `"Order"`. The binding is by property name. Rename `IPluginMetadata.Capability` to `a` and MEF looks for a key `"a"` that was never written, so the view reads a default (or throws, depending on the view and the MEF flavor). The metadata-view interface is part of the contract ABI for exactly the same reason the plugin interface is — keep it on the contract assembly and preserve its member names.

## Catalog and assembly scanning

It is tempting to think the catalog is where obfuscation bites, because a `DirectoryCatalog` scans `*.dll` by path and reflects over types. It is not. A catalog's only job is to enumerate parts and hand each one's export/import definitions to the container; it introduces no second match key. `AssemblyCatalog`, `DirectoryCatalog`, and `TypeCatalog` all funnel through the same attributed-model code that derives contract names — so the breakage is identical across them and the fix is the same. Two things about scanning are still worth stating:

- **Renaming the concrete part type is fine.** The catalog discovers `UpperPlugin` by reflecting over the assembly, not by its name; MEF never needs the part's type name to match an import once the contract name is pinned. Let it rename to `b`.
- **Do not strip or seal what the catalog must still reflect.** The part must remain a public, constructible type with its importing constructor intact, and MEF2 (`System.Composition`) resolves the constructor it marks with `[ImportingConstructor]`. Preserve that constructor's shape; its *body* is free to harden.

The two MEF flavors differ only in surface, not in this mechanism. Classic MEF (`System.ComponentModel.Composition`, `CompositionContainer` + catalogs) and lightweight MEF2 (`System.Composition`, `ContainerConfiguration` + `CompositionHost`) both resolve by contract name derived from the type name unless you pass an explicit string — so pin the string in both.

## The Nebula configuration

Two assemblies, two profiles. The contract assembly preserves its public surface — the plugin interface, the metadata-view interface, and their members — and excludes the contract-name constant from string encryption so the literal survives verbatim. The host assembly renames with nothing kept.

```xml
<Nebula>
  <!-- Host: nothing here is part of the composition ABI. -->
  <Assembly file="Host.dll">
    <Rename enabled="true" />
    <ControlFlow enabled="true" />
    <StringEncryption enabled="true" />
  </Assembly>
  <!-- Contract: the published composition ABI. -->
  <Assembly file="Contract.dll">
    <Rename enabled="true">
      <!-- IPlugin, IPluginMetadata and their members are matched by name. -->
      <Preserve names="public" members="all" />
    </Rename>
    <ControlFlow enabled="true" />
    <StringEncryption enabled="true">
      <!-- The explicit contract name must stay a plain literal. -->
      <Exclude member="MyApp.Contracts.PluginContract::Name" />
    </StringEncryption>
  </Assembly>
</Nebula>
```

The plugin assembly itself — the concrete parts like `UpperPlugin`, their private helpers and their method bodies — is renamed and hardened in full; none of those names are matched by MEF once the contract string is explicit. Preserving the contract's *names* does not mean leaving it soft: the method bodies on any abstract base, default interface members, and internal helpers in `Contract.dll` are still control-flow-obfuscated and string-encrypted. You freeze the composition contract and harden everything else. Build-time integration is a Nebula **Pro** feature; the free edition runs the same transforms from the CLI with caps.

## Verifying composition still resolves

The natural test — load your own plugins and check they run — rebuilds the plugins from source every CI run, so they always track the renamed contract and always pass. To catch the real failure, compose against a plugin binary built once against the shipping contract and never recompiled, and assert on the contract names directly.

```csharp
[Fact]
public void Composition_resolves_a_frozen_plugin_binary()
{
    // PdfPlugin.dll was compiled ONCE against the shipping Contract.dll
    // and checked in as a fixture. It is never rebuilt in CI.
    var catalog = new AggregateCatalog(
        new AssemblyCatalog(typeof(Host).Assembly),      // obfuscated host
        new DirectoryCatalog("fixtures"));               // frozen plugin
    using var container = new CompositionContainer(catalog);

    var host = new Host();
    container.SatisfyImportsOnce(host);

    Assert.NotEmpty(host.Plugins);                       // fails if the contract moved
    Assert.Equal("PDF", host.Plugins.Single().Run("pdf"));
}
```

Freeze one plugin binary, compose it against the obfuscated host, and the assertion fails the instant a rename reaches the contract name or a metadata-view property — in CI, where you can fix it, rather than in a customer's plugin folder, where you cannot. You can also assert on the derived string itself: `AttributedModelServices.GetContractName(typeof(IPlugin))` must still return the name the field expects, which is why pinning it to an explicit literal is the durable answer.

## Takeaway

MEF composes by a contract-name string, and the default string is the full type name of the contract — so an ordinary rename of the contract interface moves the match key and composition silently returns nothing. Pin every `[Export]` and `[Import]` to an explicit string contract so the match key stops depending on the identifier; preserve the contract interface and the metadata-view interface (and their members) on a separate contract assembly, because MEF still checks those by name; and leave the keys in `[ExportMetadata]` alone, since they are literals that never rename. Do that, and Nebula flattens every concrete part and the whole host while composition resolves exactly as it did before.

