我有一堆服务,我总是希望通过StructureMap获得一个独特的实例。现在,我可以通过配置每个类型来实现这一点:
ObjectFactory.Initialize(x =>
{
...
x.For<UserService>().AlwaysUnique();
...
});
但我真的不想为每种服务类型都这样做。所有服务类型都继承自ServiceBase
- 是否有任何方法可以将StructureMap配置为对AlwaysUnique()
继承的所有类型使用ServiceBase
?
答案 0 :(得分:2)
我认为你需要创建一个约定来实现这个目标:
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);
}
}
}
在扫描中应用约定:
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()));