简体   繁体   English

识别解析实例的依存关系-IoC(autofac)

[英]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. 我想对于在多个依赖关系之间共享的单个实例可能有点棘手,但我专门在寻找按依赖关系解析的实例,因此在上面的示例中将有两个B实例。

FWIW, my IoC container is Autofac and it is running in the context of an MVC web app FWIW,我的IoC容器是Autofac,它在MVC Web应用程序的上下文中运行

You can use the ResolveOperationBegging and InstanceLookupBeginning events 您可以使用ResolveOperationBeggingInstanceLookupBeginning事件

    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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM