[英]Mapping Interfaces to concrete classes
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.
使用Unity DI,我需要注册具体的类及其实现的接口。 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: 如果您使用的是Unity 3,则可以按约定使用注册,这可以简化代码:
container.RegisterTypes(
AllClasses.FromLoadedAssemblies()
.Where(a => a.FullName.Contains("Romabravo.ApplicationManager")),
WithMappings.FromMatchingInterface);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.