在我的注册表中我有
Scan(scanner =>
{
scanner.AssemblyContainingType<EmailValidation>();
scanner.ConnectImplementationsToTypesClosing(typeof(IValidation<>));
});
我应该怎样做才能将这些全部定义为单身人士?
另外,对于这个问题,有没有理由不将无状态的所有内容定义为在StructureMap中注册的单例对象?
答案 0 :(得分:12)
凯文的答案对于2.5.4及更早版本是正确的。在当前的StructureMap主干中(当发布2.5.5+时),您现在可以执行:
Scan(scanner =>
{
scanner.AssemblyContainingType<EmailValidation>();
scanner.ConnectImplementationsToTypesClosing(typeof(IValidation<>))
.OnAddedPluginTypes(t => t.Singleton());
});
答案 1 :(得分:1)
程序集扫描程序方法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<>));
});
希望这有帮助。