I have written the following piece of code and I'm looking to refine it. using Unity DI, I need to register concrete classes along with the interfaces they implement. The advantage of the method is to remove the need to keep registering new classes when added.
I have reduced the code to
IUnityContainer container = new UnityContainer(); // from // Factories // container.RegisterType(); // Services // container.RegisterType(); // container.RegisterType(); //...... // to var assemblies = AppDomain.CurrentDomain.GetAssemblies() .Where(x => x.GetName().Name.Contains("Romabravo.ApplicationManager")); foreach (var assembly in assemblies) { var types = assembly.GetExportedTypes(); foreach (Type t in types) { var interfaces = t.GetInterfaces().Where(x => x.FullName != null && x.FullName.Contains("Romabravo.ApplicationManager")).ToList(); foreach (var item in interfaces) { var interfaceImplementers = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s => s.GetTypes()) .Where(p => item.GetTypeInfo().IsAssignableFrom(p) && item.FullName.Contains("Romabravo.ApplicationManager")) .Select(x => x).Where(x => !x.IsInterface && !x.IsAbstract).ToList(); if (interfaceImplementers != null) { foreach (var implementer in interfaceImplementers) { container.RegisterType(item, implementer); } } } } } return container;
Just looking for a way to optimise it further.
If you are using Unity 3 then you can use registration by convention which could simplify the code a bit:
container.RegisterTypes(
AllClasses.FromLoadedAssemblies()
.Where(a => a.FullName.Contains("Romabravo.ApplicationManager")),
WithMappings.FromMatchingInterface);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.