Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-register all interfaces with Unity

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?
like image 217
David Avatar asked Mar 14 '12 12:03

David


3 Answers

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);
}
like image 173
aallalajr Avatar answered Oct 18 '22 08:10

aallalajr


I wanted the same as you; convention based configuration ala Structuremap, and went ahead and created a library for it. You can download it on NuGet, and read some documentation on my github page

Hope this helps!

like image 33
thedersen Avatar answered Oct 18 '22 07:10

thedersen


Unity does not have support for conventions. But the TecX project on codeplex contains an enhanced configuration engine for Unity that is based on StructureMap's configuration.

like image 1
Sebastian Weber Avatar answered Oct 18 '22 06:10

Sebastian Weber