Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify the dependency resolving an instance - IoC (autofac)

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

like image 597
Baz1nga Avatar asked Dec 04 '25 14:12

Baz1nga


1 Answers

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
like image 61
Cyril Durand Avatar answered Dec 07 '25 12:12

Cyril Durand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!