Question

Is there any option to create singletons for, say, every class that implement interfaces from specified namespace? At the moment all I can do is:

ObjectFactory.Configure(c =>
        {
            c.Scan(x =>
            {
                x.Assembly("SomeAssembly");

                x.WithDefaultConventions();
            });                
        });

I want this configuration to provide singletons for business services, that need to be created only once.

Was it helpful?

Solution 2

Here's the actual implementation:

public class ServiceSingletonConvention : DefaultConventionScanner
{
    public override void Process(Type type, Registry registry)
    {
        base.Process(type, registry);

        if (type.IsInterface || !type.Name.ToLower().EndsWith("service")) return;

        var pluginType = FindPluginType(type); // This will get the interface

        registry.For(pluginType).Singleton().Use(type);
    }
}

You'll have to use it this way:

ObjectFactory.Configure(c =>
{
   c.Scan(x =>
   {
       x.Assembly("SomeAssembly");

       x.Convention<ServiceSingletonConvention>();
   });                
});

Hope you'll find this useful.

OTHER TIPS

There are several ways that you could solve this problem while still using assembly scanning.

Use StructureMap Custom Attributes

[PluginFamily(IsSingleton = true)]  
public interface ISomeBusinessService
{...

This is has advantages and disadvantages. It is pretty simple to use and doesn't require a lot of knowledge of the inner workings of StructureMap. The downside is that you have to decorate your interface declarations and you'll have to reference StructureMap in your business services assembly.

Implement a custom ITypeScanner

public interface ITypeScanner  
{  
    void Process(Type type, PluginGraph graph);  
}

This can accomplish what you want to do without having to decorate your interfaces or have a reference to StructureMap in your business services assembly. However, this does require you to implement the registration process for types in the assembly. For more information see the StructureMap website Custom Scanning Conventions. If you need additional help, I can elaborate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top