确定解析实例的依赖关系 – IoC(autofac)
有没有办法确定哪个调用者/依赖项正在解析它所依赖的实例? 这就是我的想法
public class A { public A() { Console.Write("I am being resolved by {0}"); } } public class B { public B(A a) { //Should print: A being resolved by B } } public class C { public C(A a) { //Should print: A being resolved by C } }
我猜测在多个依赖项之间共享的单个实例可能有点棘手,但我特意寻找每个依赖项解析的实例,因此在上面的示例中将有两个B实例。
FWIW,我的IoC容器是Autofac,它在MVC Web应用程序的上下文中运行
您可以使用ResolveOperationBegging
和InstanceLookupBeginning
事件
ContainerBuilder builder = new Autofac.ContainerBuilder(); builder.RegisterType().AsSelf(); builder.RegisterType().AsSelf(); builder.RegisterType().AsSelf(); IContainer container = builder.Build(); EventHandler lifetimeScopeBeginning = null; lifetimeScopeBeginning = (sender, e) => { e.LifetimeScope.ResolveOperationBeginning += (sender2, e2) => { List activators = new List (); e2.ResolveOperation.InstanceLookupBeginning += (sender3, e3) => { activators.Add(e3.InstanceLookup.ComponentRegistration.Activator); Console.WriteLine("Activation Path : {0}", String.Join(" => ", activators.Select(a => a.LimitType.Name).ToArray())); }; }; e.LifetimeScope.ChildLifetimeScopeBeginning += lifetimeScopeBeginning; }; container.ChildLifetimeScopeBeginning += lifetimeScopeBeginning; using (ILifetimeScope scope = container.BeginLifetimeScope()) { scope.Resolve(); }
此代码将显示
Activation Path : C Activation Path : C => B Activation Path : C => B => A