程序集掃描器方法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