Auto-register all interfaces with Unity

David picture David · Mar 14, 2012 · Viewed 9.6k times · Source

Using Unity, I'd like to automatically register all interface/class combinations in an assembly based on the following convention:

INameOfObject > NameOfObject

StructureMap does that when the default conventions are enabled.

I wrote the following method for it:

private static IUnityContainer RegisterITypesOf(this IUnityContainer container, string assemblyName)
{
  Assembly.Load(assemblyName)
    .GetTypes()
    .Where(t => t.GetInterfaces().Any(i => i.Name == "I" + t.Name))
    .ForEach(t => container.RegisterType(t.GetInterface("I" + t.Name, false), t));
  return container;
}

My question is:

  • is there a built-in function that does the same?
  • if not, can my code be improved performance wise?

Answer

aallalajr picture aallalajr · Apr 24, 2015

Unity 3.5.140.0 has built in functionality to register interfaces with similar names as the class that uses it.

public static void RegisterTypes(IUnityContainer container)
{
    container.RegisterTypes(
    AllClasses.FromLoadedAssemblies(),
    WithMappings.FromMatchingInterface,
    WithName.Default);
}