程序集扫描器方法 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<>));
});
希望这可以帮助。