Search code examples
autofac

Keyed registration with implicit types and no defaults


When I register a type with autofac and use PreserveExistingDefaults, it registers a default for T if no previous registrations for that type exist. I know this is how it is intended, but is there a way to have it not register a default at all, but still get registered for implicit types?

My use case is that I want to (1) force consumers of type T to rely on a keyed registration (i.e. throw an exception if T is requested without a key filter), and (2) I also want those registrations to show up in IEnumerable<T> implicit injections.

I saw in this answer that I can just add an As<T> registration to accomplish (2), but it also registers a default so I don't get (1).


Solution

  • Unfortunately, this is not a use case Autofac addresses.

    I might suggest that there's a logic flaw in the design anyway. If a developer can't resolve a single T without a key, but they can resolve all the T without keys, then folks will simply work around the problem by resolving all of them and manually choosing the one they want. I would recommend revisiting the requirements so you don't have the situation you describe.