Cocowalla
Cocowalla

Reputation: 14331

Get unique instance of types inheriting from base class with StructureMap

I have a bunch of services for which I always want to get a unique instance with StructureMap. Now, I can get this working by configuring each type like:

ObjectFactory.Initialize(x =>
{
  ...

  x.For<UserService>().AlwaysUnique();

  ...
});

But I don't really want to do that for every service type. The service types all inherit from ServiceBase - is there any way to configure StructureMap to use AlwaysUnique() for all types that inherit from ServiceBase?

Upvotes: 1

Views: 569

Answers (1)

PHeiberg
PHeiberg

Reputation: 29811

I think you need to create a convention to achieve this:

using StructureMap.Pipeline;
using StructureMap.TypeRules;
using StructureMap.Configuration.DSL;

public class ConcreteLifecycleConvention : StructureMap.Graph.IRegistrationConvention
{
    private readonly Type _baseType;
    private readonly ILifecycle _lifecycle;

    public ConcreteLifecycleConvention(Type baseType, ILifecycle lifecycle)
    {
        _baseType = baseType;
        _lifecycle = lifecycle;
    }

    public void ScanTypes(TypeSet types, Registry registry)
    {
        foreach(var type in types.AllTypes())
        {
            if (type.IsAbstract || !type.CanBeCreated() || !type.CanBeCastTo(_baseType))
                continue;

            registry.For(type).LifecycleIs(_lifecycle);
        }
    }
}

Apply the convention in a scan:

ObjectFactory.Initialize(c =>
{
    c.Scan(scan =>
    {
        scan.TheCallingAssembly();
        scan.With(new ConcreteLifecycleConvention(typeof(ServiceBase), 
            new UniquePerRequestLifecycle()));
    });
});

As a side note. With the built in conventions you can use the OnAddedPluginTypes to specify the lifecycle, but there is no built in convention that registers the concretes that is registered without an interface

scan.WithDefaultConventions().OnAddedPluginTypes(x => 
    x.LifecycleIs(new UniquePerRequestLifecycle()));

Upvotes: 2

Related Questions