我编写了以下代码,我正在寻求改进它。使用Unity DI,我需要注册具体的类以及它们实现的接口。该方法的优点是无需在添加时继续注册新类。
我已将代码缩减为
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;
只是想方设法进一步优化它。
答案 0 :(得分:2)
如果您使用的是Unity 3,那么您可以使用registration by convention来简化代码:
container.RegisterTypes(
AllClasses.FromLoadedAssemblies()
.Where(a => a.FullName.Contains("Romabravo.ApplicationManager")),
WithMappings.FromMatchingInterface);