程序集扫描器方法ConnectImplementationsToTypesClosing使用IRegistrationConvention完成工作。为此,我复制并更新了StructureMap通用连接扫描程序,以获取范围。接下来,我创建了一个方便的装配扫描仪扩展方法,以用作语法糖来连接它。
public class GenericConnectionScannerWithScope : IRegistrationConvention
{
private readonly Type _openType;
private readonly InstanceScope _instanceScope;
public GenericConnectionScannerWithScope(Type openType, InstanceScope instanceScope)
{
_openType = openType;
_instanceScope = instanceScope;
if (!_openType.IsOpenGeneric())
{
throw new ApplicationException("This scanning convention can only be used with open generic types");
}
}
public void Process(Type type, Registry registry)
{
Type interfaceType = type.FindInterfaceThatCloses(_openType);
if (interfaceType != null)
{
registry.For(interfaceType).LifecycleIs(_instanceScope).Add(type);
}
}
}
public static class StructureMapConfigurationExtensions
{
public static void ConnectImplementationsToSingletonTypesClosing(this IAssemblyScanner assemblyScanner, Type openGenericType)
{
assemblyScanner.With(new GenericConnectionScannerWithScope(openGenericType, InstanceScope.Singleton));
}
}
下面是相应的设置代码。
Scan(scanner =>
{
scanner.ConnectImplementationsToSingletonTypesClosing(typeof(IValidation<>));
});
希望这会有所帮助。
非常不错的添加功能,不能等待2.5.5! – 2010-01-31 22:01:11
切换到这个答案更符合当前时代。 – 2011-07-25 17:12:36