6

在我的注册表中,我有

Scan(scanner =>
         {
             scanner.AssemblyContainingType<EmailValidation>();
             scanner.ConnectImplementationsToTypesClosing(typeof(IValidation<>));
         });

我应该怎么做才能将这些都定义为单例?

另外,除了这个问题,是否有任何理由不将无状态的所有内容定义为在 StructureMap 中注册的单例对象?

4

2 回答 2

12

Kevin 的回答对于 2.5.4 及更早版本是正确的。在当前的 StructureMap 主干中(以及发布 2.5.5+ 时),您现在可以执行以下操作:

Scan(scanner =>
{
   scanner.AssemblyContainingType<EmailValidation>();
   scanner.ConnectImplementationsToTypesClosing(typeof(IValidation<>))
          .OnAddedPluginTypes(t => t.Singleton());
});
于 2010-01-30T19:18:04.350 回答
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<>));
     });

希望这可以帮助。

于 2010-01-25T20:17:06.280 回答