StructureMap: how to set the life cycle for types associated with ConnectImplementationsToTypesClosing

In my registry I have

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

What should I do to define all this as Singletons?

Also, aside from this question, is there any reason not to define everything that is stateless as a singleton object registered in StructureMap?

+5
source share
2 answers

Kevin's answer is correct for versions 2.5.4 and later. In the current StructureMap structure (and when 2.5.5+ is issued), you can now do:

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

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

, .

+1

All Articles