Identify the dependency resolving an instance - IoC (autofac)

asp.net-mvc, autofac, c#, dependency-injection

Solution

You can use the `ResolveOperationBegging` and `InstanceLookupBeginning` events

    ContainerBuilder builder = new Autofac.ContainerBuilder();
    builder.RegisterType<A>().AsSelf();
    builder.RegisterType<B>().AsSelf();
    builder.RegisterType<C>().AsSelf();

    IContainer container = builder.Build();

    EventHandler<LifetimeScopeBeginningEventArgs> lifetimeScopeBeginning = null;
    lifetimeScopeBeginning = (sender, e) =>
    {
        e.LifetimeScope.ResolveOperationBeginning += (sender2, e2) =>
        {
            List<IInstanceActivator> activators = new List<IInstanceActivator>();
            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<C>();
    }

This code will display

Activation Path : C
Activation Path : C => B
Activation Path : C => B => A

Problem

Is there a way to identify which caller/dependency is resolving an instance that it is dependent on? here is what I am thinking ``` 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 } } ``` I am guessing for a single instance that is shared across multiple dependency it might be a little tricky but I am specifically looking for instances resolved per dependency so in the above example there will be two instances of B. FWIW, my IoC container is Autofac and it is running in the context of an MVC web app

Original source