2010-01-25 46 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