Search code examples
c#unity-container

How to resolve all implementations of one interface in unity?


Okay, I want to create arbitrary implementations of a specific Interface and resolve them. It's actually similiar to a plugin system. "Create your own Implementation of intereface X and the app does the rest"

public interface IMenuEntry { ... }

// auto-mapping (registration-by-convention)
_container.RegisterTypes(AllClasses.FromAssemblies(assemblies), 
                         WithMappings.FromMatchingInterface, 
                         // ResolveAll need names for multiple registrations of the same type (?)
                         WithName.TypeName,                 
                         WithLifetime.ContainerControlled);

var g = _container.ResolveAll<IMenuEntry>(); // empty - why?


When I check my container registrations my implemantations are there and the name is the name of the class - not the interface. Wonderful. But why can't I resolve all implementations of IMenuEntry? It is always empty.


Solution

  • WithMappings.FromMatchingInterface will only match a type named MenuEntry to IMenuEntry.

    You might try WithMappings.FromAllInterfaces instead.

    See the WithMappings methods documentation.