0

我有一堆服務,我總是希望得到一個獨特的StructureMap實例。現在,我可以通過配置各類型一樣得到這個工作:獲取從基類繼承的類型的唯一實例與StructureMap

ObjectFactory.Initialize(x => 
{ 
    ... 

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

    ... 
}); 

但我真的不希望這樣做,對於每一個服務類型。服務類型都從ServiceBase繼承 - 有沒有什麼辦法可以將StructureMap配置爲使用AlwaysUnique()來繼承從ServiceBase繼承的所有類型?

回答

0

我認爲你需要創建一個約定來實現這一目標:

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 Process(Type type, Registry registry) 
    { 
     if (type.IsAbstract || !type.CanBeCreated() || !type.CanBeCastTo(_baseType)) 
      return; 

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

適用公約在掃描:

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

補充說明。通過內置的約定,您可以使用OnAddedPluginTypes來指定生命週期,但是沒有內置約定記錄沒有接口的註冊混凝土。

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