How to build a graph of resolved instances with Au

2019-08-30 01:39发布

问题:

After all registrations, I am doing ContainerBuilder.RegisterCallback and subscribing to all IComponentRegistration.Preparing and IComponentRegistration.Activating events to be able to handle all activations. With this two events I am able to build a tree, the order of events looks like this:

  • Preparing: Root
    • Preparing: FirstLevel_A
    • Activating: FirstLevel_A
    • Preparing: FirstLevel_B
      • Preparing: SecondLevel_C
      • Activating: SecondLevel_C
    • Activating: FirstLevel_B
  • Activating: Root

But what if some registrations are not Per Dependency and I will have a graph instead of a tree. Is it possible to handle this case?

回答1:

Not an answer, but it is too big for a comment.

AutoFac is a great IoC container, but it has 2 major problems. One is the awful registration API and the other one is a complete lack of diagnostics. The original author of AutoFac once tried to create an application that would help with this: Whitebox. The development has stopped and moved on to Autofac Analysis, that hasn't been active in years.

What you want to do requires a lot of insight into the inner workings of AutoFac, so you might want to check out the sources for ideas on how to accomplish what you need.



回答2:

According to this answer there's another way of handling these events:

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.

It's harder, but should do the job.