6

私のレジストリには

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

これらすべてをシングルトンとして定義するにはどうすればよいですか?

また、この質問の余談ですが、ステートレスなものすべてを StructureMap に登録されているシングルトン オブジェクトとして定義しない理由はありますか?

4

2 に答える 2

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 に答える