你要找的是
自动注册
. 大多数容器允许您在基于
惯例
或者执行未注册的类型解析并查找缺少的类型。
例如,可以搜索程序集并注册启动期间与约定匹配的所有类型:
var container = new Container();
Assembly assembly = typeof(Thing).Assembly;
var mappings =
from type in assembly.GetExportedTypes()
let matchingInterface = "I" + type.Name
let service = type.GetInterfaces().FirstOrDefault(i => matchingInterface)
where service != null
select new { service, type };
foreach (var mapping in mappings)
{
// Register the type in the container
container.Register(mapping.service, mapping.type);
}
使用未注册的类型解析,您可以动态注册。如何做到这一点在很大程度上取决于您使用的容器。例如,对于简单的注入器,如下所示:
var container = new Container();
Assembly assembly = typeof(Thing).Assembly;
container.ResolveUnregisteredType += (s, e)
{
Type service = e.UnregisteredServiceType;
if (service.IsInterface)
{
var types = (
from type in asssembly.GetExportedTypes()
where service.IsAssignableFrom(type)
where !type.IsAbstract
where service.Name == "I" + type.Name
select type)
.ToArray();
if (types.Length == 1)
{
e.Register(Lifestyle.Transient.CreateRegistration(types[0], container));
}
}
};
这两种方法都不需要不断更新容器配置。