2010-01-25 44 views

回答

11

凯文的回答对版本2.5.4及更高版本是正确的。在当前StructureMap干线(和2.5.5+被释放时),你现在可以做的:

Scan(scanner => 
{ 
    scanner.AssemblyContainingType<EmailValidation>(); 
    scanner.ConnectImplementationsToTypesClosing(typeof(IValidation<>)) 
      .OnAddedPluginTypes(t => t.Singleton()); 
}); 
+0

非常不错的添加功能,不能等待2.5.5! – 2010-01-31 22:01:11

+0

切换到这个答案更符合当前时代。 – 2011-07-25 17:12:36

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<>)); 
    }); 

希望这会有所帮助。

+0

这肯定看起来像一个解决方案,这是愚蠢的,这需要对于这么简单的东西做然而,这看起来非常相似对于我之前在SM小组看到的文章,我认为Jeremy可能会添加一种方法来指定,而无需在2.5.5中实现自己的约定,现在看到您的文章后,它就会非常有意义。 – 2010-01-25 23:49:29

+0

抱歉没有看到该帖子。我和杰里米一起工作。为了创建我的解决方案,我只抓住了StructureMap的源代码,并想出了他是如何做到这一点,并根据您的要求进行调整的。它可能受益于更多的灵活性或更好的与SM配置DSL的集成,但这会让你现在就开始。请享用。 – KevM 2010-01-25 23:57:31