我認爲你需要創建一個約定來實現這一目標:
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()));