确定的依赖解决的一个实例 - IOC(autofac) [英] Identify the dependency resolving an instance - IoC (autofac)

查看:266
本文介绍了确定的依赖解决的一个实例 - 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
    }
}

我猜对跨多个依赖共享的单个实例这可能是一个有点棘手,但我专门找了每个依赖解决,以便在上面的例子中会出现的B两个实例的实例。

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,我的IoC容器是Autofac,它是在MVC的Web应用程序的

FWIW, my IoC container is Autofac and it is running in the context of an MVC web app

推荐答案

您可以使用 ResolveOperationBegging InstanceLookupBeginning 事件

    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>();
    }

这code将显示

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

这篇关于确定的依赖解决的一个实例 - IOC(autofac)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆