title: In Autofac, how do I replace the default registration with a decorator?
body: <p>I ran in to some unexpected behaviour in Autofac (v4.4.0, .NET 4.6.1), which I feel may be a bug.</p>
  
  <p>From the <a href="http://docs.autofac.org/en/latest/register/registration.html#default-registrations" rel="nofollow noreferrer">documentation</a>:</p>
  
  <blockquote>
    <h3>Default Registrations</h3>
    
    <p>If more than one component exposes the same service, <strong>Autofac will use the last registered component as the default provider of that service</strong>:</p>
  </blockquote>
  
  <p>e.g. If I do this:</p>
  
  <pre><code>    builder.RegisterType&lt;FooOne&gt;().As&lt;IFoo&gt;();
      // Next line replaces default IFoo implementation
      builder.RegisterType&lt;FooTwo&gt;().As&lt;IFoo&gt;();
  </code></pre>
  
  <p>I expect (and get) an instance of <code>FooTwo</code> when I resolve <code>IFoo</code> from the container.</p>
  
  <p>However, if I have already registered an <code>IFoo</code>, and I use the <code>RegisterDecorator&lt;T&gt;</code> function to register a decorator of <code>IFoo</code>, it <em>does not</em> replace the default registration of <code>IFoo</code>. e.g:</p>
  
  <pre><code>    // Register FooOne directly
      builder.RegisterType&lt;FooOne&gt;().As&lt;IFoo&gt;(); // (1)
      // Now set up a decorator
      builder.RegisterType&lt;FooOne&gt;().Named&lt;IFoo&gt;("foo");
      builder.RegisterDecorator&lt;IFoo&gt;((c, inner) =&gt;
        new DecoratorFoo(inner), fromKey: "foo");
  </code></pre>
  
  <p>Will resolve <code>IFoo</code> as an <strong><em>undecorated</em></strong> <code>FooOne</code>. This feels inconsistent to me; a violation of the <a href="https://en.wikipedia.org/wiki/Principle_of_least_astonishment" rel="nofollow noreferrer">principle of least astonishment</a>.</p>
  
  <p>You might claim that I shouldn't have line (1) at all (and the code works correctly without it) - but it's an accepted idiom (e.g. <a href="https://stackoverflow.com/questions/15754702/override-autofac-registration-with-plugin?rq=1">here</a>) to use a plug-in to replace registrations.</p>
  
  <p>In my case, this bug manisfested in a fairly large codebase where the wrapped type was already registered by a convention and, now needing to be decorated, requires a significant re-think of how registration is done.</p>
  
  <p>A Gist suitable for LINQPad demonstrating the issue is <a href="https://gist.github.com/james-world/571c11b64f28baa6e27a44b818787ac3" rel="nofollow noreferrer">here</a>.</p>
  
  <p>Is there any design reason for the observed behaviour that I am missing? Is there a way to have the decorator registration replace the default?</p>