我正在使用Simple Injector,以使我的代码能够自动连接到事件总线消息。在自动布线期间,我INotificationHandlers
允许将不同的生活方式潜在地用于不同的具体实现,如下所示:
public static Lifestyle GetLifestyleForType(
Type type, Container container, Dictionary<Type,Lifestyle> list = null)
{
if (list is null) return container.Options.DefaultLifestyle;
return list.TryGetValue(type, out var lifestyle)
? lifestyle : container.Options.DefaultLifestyle;
}
public static void Wire(Container container)
{
var lifestyles = new Dictionary<Type, Lifestyle> {
{ typeof(FirstClass), Lifestyle.Singleton },
{ typeof(OtherClass), Lifestyle.Transient }
};
var handlerTypes = container
.GetTypesToRegister(typeof(INotificationHandler<>), typeof(OtherClass).Assembly);
var handlerProducers = (
from type in handlerTypes
from interfaceType in type.GetClosedTypesOf(typeof(INotificationHandler<>))
let producer = GetLifestyleForType(type, container, lifestyles)
.CreateProducer(interfaceType, type, container)
group new { type, producer } by interfaceType into interfaceGroup
select new
{
interfaceGroup.Key,
Value = (
from pair in interfaceGroup
group pair.producer by pair.type into concreteGroup
select new { concreteGroup.Key, Value = concreteGroup.ToArray() })
.ToDictionary(i => i.Key, i => i.Value)
}).ToDictionary(i => i.Key, i => i.Value);
}
我注意到,在所有其他自动接线示例中,都假定使用了相同的生活方式(尚未看到指定的生活方式)-出于任何原因(防止做危险的事情)?
另外,Lifestyle.Transient
与async/await
运营商的工作方式不同吗?我刚刚意识到一直在使用Transient
生命周期,SimpleInjector
而没有我知道的任何不良影响,假设我默认情况下应切换到Lifestyle.Scoped
和(如我上面的接线)container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle()
我注意到,在所有其他自动接线示例中,都假定使用了相同的生活方式(尚未看到指定的生活方式)-出于任何原因(防止做危险的事情)?
默认情况下,Simple Injector使用Transient
默认生活方式。这意味着,除非您明确提供生活方式的注册信息,否则Simple Injector会使用默认的生活方式,即Transient
。
尽管为操作员使用多种生活方式并没有天生的错误,但是使用多种生活方式确实会增加解决方案的复杂性(您可能已经注意到),因此您应该问自己是否真的需要这种复杂性。除非您希望使对象图从上到下都是单例(但这会导致模型完全不同),否则我建议保持解决方案简单,并坚持使用Transient
替代方法。作为一般经验法则,请设置您的根类型(处理程序,控制器,视图模型等)Transient
。
但是,Transient
生活方式会带来一些后果。Transient
组件不会被丢弃,并且由于Transient
组件不会被重用,因此它们不能用于任何数据缓存。
但是,可以通过将任何有关处理和缓存的逻辑移到根类型的依赖项来轻松解决这些问题。您可以使这些依赖项Scoped
甚至是Singleton
。我通常会对系统中在IDisposable
内部实现或缓存任何状态的任何处理程序不满意。将这种逻辑移出处理程序,不仅可以“解决”Transient
生活方式的局限性,而且我认为这将导致设计更好的系统。这也使推理处理程序变得更加容易。他们可以做什么,不能做什么以及他们的生活方式是什么。对于所有在系统上工作的开发人员(以及将来的任何开发人员),最容易理解的是所有处理程序始终具有相同的生活方式。
另外,Lifestyle.Transient与异步/等待操作员的工作方式是否有所不同?
的Transient
生活方式是有最简单的生活方式; 对于Simple Injector而言Transient
,这是无人操作的。实例已创建并被遗忘(未跟踪)。在异步操作中运行时,它不会有任何不同。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句