Identify the dependency resolving an instance - IoC (autofac)

青春壹個敷衍的年華 提交于 2019-12-08 04:05:51

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/28645099/identify-the-dependency-resolving-an-instance-ioc-autofac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!