如何使用 Autofac 构建已解析实例的图表?
How to build a graph of resolved instances with Autofac?
完成所有注册后,我正在执行 ContainerBuilder.RegisterCallback
并订阅所有 IComponentRegistration.Preparing
和 IComponentRegistration.Activating
事件,以便能够处理所有激活。通过这两个事件,我可以构建一棵树,事件的顺序如下所示:
- 准备:根目录
- 准备中:FirstLevel_A
- 正在激活:FirstLevel_A
- 准备中:FirstLevel_B
- 准备中:SecondLevel_C
- 正在激活:SecondLevel_C
- 正在激活:FirstLevel_B
- 正在激活:Root
但是,如果某些注册不是 Per Dependency
怎么办,我将使用图表而不是树。这种情况可以处理吗?
不是答案,但对于评论来说太大了。
AutoFac 是一个很棒的 IoC 容器,但它有两个主要问题。一个是糟糕的注册 API,另一个是完全缺乏诊断。 AutoFac 的原作者曾经试图创建一个应用程序来帮助解决这个问题:Whitebox. The development has stopped and moved on to Autofac Analysis,多年来一直没有活跃。
您想要完成的工作需要对 AutoFac 的内部工作原理有深入的了解,因此您可能需要查看资源以获取有关如何完成所需工作的想法。
根据 this answer,还有另一种处理这些事件的方法:
If you want to get fancier, you can set up some event handlers on the
container ChildLifetimeScopeBeginning
, ResolveOperationBeginning
,
ResolveOperationEnding
, and CurrentScopeEnding
events.
During ChildLifetimeScopeBeginning
you'd need to set up something to
automatically attach to any child lifetime ResolveOperationBeginning
events.
During ResolveOperationBeginning
you'd log what is going to be
resolved.
During ResolveOperationEnding
you'd log any exceptions
coming out.
During CurrentScopeEnding
you'd need to unsubscribe from
any events on that scope so the garbage collector can clean up the
lifetime scope with all of its instances.
这更难,但应该可以完成。
完成所有注册后,我正在执行 ContainerBuilder.RegisterCallback
并订阅所有 IComponentRegistration.Preparing
和 IComponentRegistration.Activating
事件,以便能够处理所有激活。通过这两个事件,我可以构建一棵树,事件的顺序如下所示:
- 准备:根目录
- 准备中:FirstLevel_A
- 正在激活:FirstLevel_A
- 准备中:FirstLevel_B
- 准备中:SecondLevel_C
- 正在激活:SecondLevel_C
- 正在激活:FirstLevel_B
- 正在激活:Root
但是,如果某些注册不是 Per Dependency
怎么办,我将使用图表而不是树。这种情况可以处理吗?
不是答案,但对于评论来说太大了。
AutoFac 是一个很棒的 IoC 容器,但它有两个主要问题。一个是糟糕的注册 API,另一个是完全缺乏诊断。 AutoFac 的原作者曾经试图创建一个应用程序来帮助解决这个问题:Whitebox. The development has stopped and moved on to Autofac Analysis,多年来一直没有活跃。
您想要完成的工作需要对 AutoFac 的内部工作原理有深入的了解,因此您可能需要查看资源以获取有关如何完成所需工作的想法。
根据 this answer,还有另一种处理这些事件的方法:
If you want to get fancier, you can set up some event handlers on the container
ChildLifetimeScopeBeginning
,ResolveOperationBeginning
,ResolveOperationEnding
, andCurrentScopeEnding
events.
During
ChildLifetimeScopeBeginning
you'd need to set up something to automatically attach to any child lifetimeResolveOperationBeginning
events.During
ResolveOperationBeginning
you'd log what is going to be resolved.During
ResolveOperationEnding
you'd log any exceptions coming out.During
CurrentScopeEnding
you'd need to unsubscribe from any events on that scope so the garbage collector can clean up the lifetime scope with all of its instances.
这更难,但应该可以完成。